开发者

Android: How to set the selection in a single choice AlertDialog?

I created a single choice AlertDialog with "Apply" and "Cancel" buttons. When the user presses "Cancel", I would like to set the selected item back to what it was when the dialog was first shown (I have the value stored already).

I know how to set the selected item when the dialog is first created in setSingleChoiceItems() but is there a way to set it again later?

I would like to be compatible with API l开发者_高级运维evel 7, so I'd rather not use onPrepareDialog().


Well, nobody could find a solution to my problem, so I settled for a dialog which doesn't use buttons. When the user presses an item in the list, that selection is applied and the dialog is dismissed. No need to remember previous choices or support cancelling.


You can create your dialog on the spot rather than going through showDialog and onCreateDialog. This way its always using the current selection we give to setSingleChoiceItems.

//where we display the dialog
showDialog(MYDIALOG);
AlertDialog.Builder builder = new Builder(this);
String[] choices = {"A","B","C"};
builder.setSingleChoiceItems(choices,current_choice,null);
builder.setPositiveButton("Select",null);
builder.setNegativeButton("Cancel",null);
builder.show();
...
protected Dialog onCreatDialog(int id) {
    if (id==MYDIALOG) {
        AlertDialog.Builder builder = new Builder(this);
        String[] choices = {"A","B","C"};
        builder.setSingleChoiceItems(choices,current_choice,null);
        builder.setPositiveButton("Select",null);
        builder.setNegativeButton("Cancel",null);
        return builder.show();
    }
    return null;
}


In Altert Dialog For creating single choice have you used single choice list view or radio group? If You have used Single Choice Listviwe then no need to worry. IF you have used Radio Group then you have to keep track of selected Radio Button Using Global Varialbe in your activity.


What you want to do when user click on cancel. when user click on cancel than do you want to remove selected item from list if yes then you have to do the following.

In Your listitemseleted listener

alb.setSingleChoiceItems(items, 0, new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            /* which argument is the position of the item in 
               array items you have to remove this item from items array
               Make your items array global variable.since in java array are 
               immutable you have to use arraylist.Arraylist can be converted 
               to array.*/

        }
    });

hope this will help if any question feel free to ask.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜