【问题标题】:Android dialog disappears on its ownAndroid 对话框自行消失
【发布时间】:2011-09-14 06:45:51
【问题描述】:

我正在使用以下代码来创建自己的对话框:

public void ShowMessageDialog(String str){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(str);
    builder.setCancelable(false);
    builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {          
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}

它工作正常,但在此函数中使用时,对话框会自行消失:

public void test(String str){
    ShowMessageDialog("About to start new activity");
    Intent intent = new Intent(this,PageViewer.class);
    startActivity(intent);
}

似乎新活动已创建并且显然摆脱了对话框。但为什么?活动不应该在打开新活动之前停止吗?

谢谢!

【问题讨论】:

    标签: android dialog


    【解决方案1】:

    即将触发的 Intent 不会等待您的对话被取消。因此,在显示对话框后,新的活动就开始了。你可以像这样完成你想要的:

    public void ShowMessageDialog(String str){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(str);
        builder.setCancelable(false);
        builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {          
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent(this,PageViewer.class);
                startActivity(intent);
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }
    
    public void test(String str){
        ShowMessageDialog("About to start new activity");
    }
    

    【讨论】:

    • 另外,您可能应该将 Intent 构造函数中的“this”替换为引用 Activity 或 Application Context,因为这种方式“this”适用于 DialogInterface 实例。我不确定,但我想你已经明白了。
    • 非常感谢您的回答!
    • @IgorFilippov 我不明白。你能详细解释一下“这个”吗
    猜你喜欢
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 2021-04-14
    • 1970-01-01
    相关资源
    最近更新 更多