how to set contents of setSingleChoiceItems in onPrepareDialog?

前端 未结 2 830
囚心锁ツ
囚心锁ツ 2021-02-09 09:53

Guys, in onCreateDialog i have this:

case DIALOG_REVIEW: {
    if (bundle.containsKey(\"POSITION\")) {
    final int position = bundle.getInt(\"POSITION\");
            


        
相关标签:
2条回答
  • 2021-02-09 10:20

    You need to use getListView method from AlertDialog class. Then use setItemChecked method on returned object. Example:

    alertDialog.getListView().setItemChecked(1, true);

    0 讨论(0)
  • 2021-02-09 10:32

    I just faced the same problem:

    Two solutions:

    1/ The fast and dirty

    Delete the Dialog each time you have finished with it => onPrepareDialog will not be called so you wont have problems with data update:

    protected Dialog onCreateDialog(int id) {
        ...
        case DIALOG_REVIEW: {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setTitle(names.get(position) + "'s number(s)");
            dialog.setSingleChoiceItems(phoneNums, 0,new DialogInterface.OnClickListener() {
    
                @Override
                public void onClick(DialogInterface dialog,int which) {
                // get selected item and close the dialog
                String selectedNumber = phoneNums[which];
                updateUserSelectedNumber(position , selectedNumber);
                removeDialog(DIALOG_REVIEW);
            }
        });
        return dialog.create();
    }
    

    if you prefer, you can put a onDismissListener and do the removeDialog on the dialog dismiss.


    2/ The quite pretty one

    In the onPrepareDialog method just replace the old ArrayAdapter used by the dialog by a fresh new one:

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
            case DIALOG_REVIEW:
                ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.select_dialog_singlechoice, android.R.id.text1, phoneNums);
                AlertDialog ad = (AlertDialog) dialog;
                ad.getListView().setAdapter(adapter);
            break;
            default:
                super.onPrepareDialog(id, dialog);
        }
    }
    

    I use the same method than the one used by android (the AlertController.java L. 854 of the froyo source code) to populate the dialog the first time.

    0 讨论(0)
提交回复
热议问题