AlertDialog with spinner on start of activity
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 b开发者_运维技巧y 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.
You could try AlertDialog.Builder
s 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.
精彩评论