繁体   English   中英

如何取消我的Android警报对话框?

[英]How can I tell when my Android alert dialog is cancelled?

这是我的警报:

new AlertDialog.Builder(Activity.this)
    .setMessage("You have unsaved text. Are you sure you want to leave?")
    .setCancelable(true)
    .setNegativeButton("Leave", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) 
        {
            finish();
        }
    })
    .setPositiveButton("Stay", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {}
    }).show();

请注意我如何允许警报取消: .setCancelable(true)

一旦用户按下后退按钮取消警报,我该如何运行一些代码?

根据Android网站上的AlertDialog.Builder文档,您可以使用setOnCancelListener(DialogInterface.OnCancelListener onCancelListener)方法来处理取消对话框的时间。

.setOnCancelListener(new DialogInterface.OnCancelListener() {
    @Override
    public void onCancel(DialogInterface dialog) 
    {
        // do what you need when the dialog is cancelled
    }
})

所以,你的代码将改为:

new AlertDialog.Builder(Activity.this)
    .setMessage("You have unsaved text. Are you sure you want to leave?")
    .setCancelable(true)
    .setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) 
        {
            // do what you need when the dialog is cancelled
        }
    })
    .setNegativeButton("Leave", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) 
        {
            finish();
        }
    })
    .setPositiveButton("Stay", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {}
    }).show();

暂无
暂无

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

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