Set default selected item of ListView Alert Dialog in Android

后端 未结 1 1909
隐瞒了意图╮
隐瞒了意图╮ 2020-12-20 14:45

I have created a dialog with a custom ListView that models a Spinner display, and originally it starts out with the value \"Select Gender\".

<
相关标签:
1条回答
  • 2020-12-20 14:57

    Figured it out:

    I switched from .setAdapter to .setSingleChoiceItems which has an argument for the default selection. Then all I had to do was create a global variable that got set each time I clicked an option. The global variable is initially set to -1 so no option is selected, then once I click on something it gets set to the position and the next time the dialog is created the selection reflects my previous selection. 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;
            }
    });
    
    0 讨论(0)
提交回复
热议问题