Set default Alert ListView dialog box item to Android

I created a dialog with a custom ListView that models the Spinner display, and initially it starts with the "Select gender" value.

When the dialog box opens, it will offer a choice (as a spinner). If the selection is selected again, it shows the same parameters, but does not indicate which option is already selected.

Example:
Default value: Select gender
Dialog opens without selection.
The user selects: "Male"
The user opens a dialog box ...
Dialog opens without selection.

( I would like for him to select β€œMale”, as this was the last choice )

Here is my code:

 genderItems = getResources().getStringArray(R.array.gender_array); genderAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, genderItems); genderDrop.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_DOWN) { Builder genderBuilder = new AlertDialog.Builder(Register.this) .setTitle(R.string.gender_prompt) .setAdapter(genderAdapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { inputGender.setText(genderItems[which]); dialog.dismiss(); } }); AlertDialog genderAlert = genderBuilder.create(); genderAlert.show(); genderAlert.getListView().setSelection(0); } return false; } }); 

genderAlert.getListView().setSelection(0) does not set the selected one as "Male" by default
genderAlert.getListView().setSelection(1) does not set the selected one as "Female" by default

+8
android listview alertdialog
source share
1 answer

It revealed:

I switched from .setAdapter to .setSingleChoiceItems , which has an argument for the default selection. Then I needed to create a global variable that was configured every time I clicked the option. The global variable is initially set to -1, so the option is not selected, and then when I click on something, it is set to the position, and the next time I create the dialog, the selection reflects my previous choice. See below:

 Integer selection = -1; genderItems = getResources().getStringArray(R.array.gender_array); genderAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, genderItems); genderDrop.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_DOWN) { Builder genderBuilder = new AlertDialog.Builder(Register.this) .setTitle(R.string.gender_prompt) .setSingleChoiceItems(genderAdapter, selection, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { inputGender.setText(genderItems[which]); selection = which; dialog.cancel(); } }); AlertDialog genderAlert = genderBuilder.create(); genderAlert.show(); } return false; } }); 
+19
source share

All Articles