繁体   English   中英

Android:如何在单一选项AlertDialog中设置选择?

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

我用“应用”和“取消”按钮创建了一个单选AlertDialog。 当用户按下“取消”时,我想将所选项目设置回第一次显示对话框时的状态(我已经存储了值)。

我知道如何在setSingleChoiceItems()首次创建对话框时设置所选项目,但有没有办法在以后再次设置它?

我想与API级别7兼容,所以我宁愿不使用onPrepareDialog()

好吧,没有人能找到我的问题的解决方案,所以我选择了一个不使用按钮的对话框。 当用户按下列表中的项目时,将应用该选择并取消对话框。 无需记住以前的选择或支持取消。

您可以在现场创建对话框,而不是通过showDialog和onCreateDialog。 这样它总是使用我们给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;
}

在Altert对话框中为了创建单一选项,您使用了单选列表视图还是无线电组? 如果您使用过Single Choice Listviwe,则无需担心。 如果您使用了Radio Group,那么您必须在活动中跟踪所选的单选按钮使用Global Varialbe。

用户点击取消时想要做什么。 当用户单击取消时,如果是,则要从列表中删除所选项目,则必须执行以下操作。

在您的listitemseleted侦听器中

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.*/

        }
    });

希望如果有任何问题可以随意提问,这将有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM