【问题标题】:Having trouble dismissing dialog in Android [AlertDialog]在 Android [AlertDialog] 中关闭对话框时遇到问题
【发布时间】:2013-07-13 05:21:47
【问题描述】:
final String[] choices = { "Item 1", "Item 2", "Item 3"};

final AlertDialog dialog= new AlertDialog.Builder(
    TestSubjectCalendar.this)
    .setTitle("Title")
    .setSingleChoiceItems(choices, pos, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss(); //gives error
            // MORE CODE
        }
    }).create();
    dialog.show();

dialog.dismiss() 出现以下错误:

局部变量对话框可能尚未初始化

我想要的是,当我从dialog 的选择列表中单击一个项目时,dialog 应该消失。那我该怎么做呢?

PS:我知道我可以使用setItems() 而不是setSingleChoiceItems(),但我想使用后者,因为它提供了单选按钮。

【问题讨论】:

  • 你能在哪个事件中显示完整的代码吗?

标签: android dialog android-alertdialog


【解决方案1】:

您需要更改对话框的名称,因为 onClick() 中的 AlertDialogDialogInterface 使用相同的名称...

尝试以下更改并进行检查。

 @Override
 public void onClick(DialogInterface dialog1, int which) {
      dialog1.dismiss(); //gives error
      // MORE CODE
 }

即解决名称覆盖,我只是在onClick()中将dialog更改为dialog1

【讨论】:

    【解决方案2】:

    试试这个:

     final String[] choices = { "Item 1", "Item 2", "Item 3"};
    
    final AlertDialog.Builder dialog= new AlertDialog.Builder(TestSubjectCalendar.this);
    
    dialog.setTitle("Title")
    .setSingleChoiceItems(choices, pos, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss(); //gives error
            // MORE CODE
        }
    }).create();
    dialog.show();
    

    【讨论】:

    • 我也试过这个。但这给出了错误Type mismatch: cannot convert from AlertDialog.Builder to AlertDialog
    • 现在这个错误:The method dismiss() is undefined for the type AlertDialog.Builder
    【解决方案3】:

    基本上,由于您在初始化对话框的同一代码块中引用对话框,Eclipse/Java 编译器担心onClick(DialogInterface dialog, int which) 中使用的对话框引用可能无效。

    所以改成:

        final AlertDialog dialog= new AlertDialog.Builder(
                TestSubjectCalendar.this).create();
                dialog.setTitle("Title");
                dialog.setSingleChoiceItems(choices, pos, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss(); //gives error
                        // MORE CODE
                    }
                });
                dialog.show();
    

    应该可以解决问题。附带说明一下,您的代码实际上没有任何错误,可能与编译器设置有关。

    【讨论】:

    • 执行您所写的操作会出现以下错误:Type mismatch: cannot convert from AlertDialog.Builder to AlertDialog
    猜你喜欢
    • 1970-01-01
    • 2017-02-19
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多