AlertDialog with spinner on start of activity

2019-04-16 11:21发布

I am trying to create an AlertDialog with a spinner on the start of an activity. I have the following code within the activity's onCreate() method.

  AlertDialog.Builder builder = new AlertDialog.Builder(this);
 AlertDialog alertDialog;
 Context mContext = getApplicationContext();
 LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
 View layout = inflater.inflate(R.layout.custom_dialog,
                                (ViewGroup) findViewById(R.id.layout_root));

 Spinner spinner = (Spinner) layout.findViewById(R.id.spinner);
 ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
         this, R.array.num_players_array, android.R.layout.simple_spinner_item);
 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 spinner.setAdapter(adapter);

 builder = new AlertDialog.Builder(mContext);
 alertDialog = builder.create();
 alertDialog.show();

This force closes every time. I have successfully created a simple AlertDialog on the start of an activity by using the following code:

 AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Stackoverflow!").create().show();

I would greatly appreciate it if someone could point me in the right direction.

1条回答
爷、活的狠高调
2楼-- · 2019-04-16 12:01

You could try AlertDialog.Builders setView() method to set your created View layout as the dialog's view.

builder.setView(layout);

In any case, it might be helpful to post the output of adb logcat to find out what exception is crashing your app.

查看更多
登录 后发表回答