AlertDialog with spinner on start of activity

和自甴很熟 提交于 2019-12-22 00:18:33

问题


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:


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.



来源:https://stackoverflow.com/questions/5132512/alertdialog-with-spinner-on-start-of-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!