Android在BackPressed上提示AlertDialog

时间:2012-06-05 22:33:17

标签: android android-alertdialog

我正在尝试在我的应用程序中完成主菜单。我认为在OnBackPressed方法中添加AlertDialog是一个简单的好方法。但由于某种原因,我遇到了各种各样的错误。

我在OnBackPressed中创建了AlertDialog并显示它,但是当我按下后退按钮时,应用程序才关闭,我收到错误消息,说窗口正在泄漏。

知道怎么解决这个问题吗?我搜索了大约30分钟,找不到其他人遇到这个问题。

4 个答案:

答案 0 :(得分:35)

尽量不要调用 super.OnBackPressed(),这段代码应该有所帮助:

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you want to exit?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    MyActivity.this.finish();
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });
    AlertDialog alert = builder.create();
    alert.show();

}

答案 1 :(得分:6)

如果要调用super.onBackPressed(),请使用以下代码:

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you want to exit?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    //finish();
                    MyActivity.this.onSuperBackPressed();
                    //super.onBackPressed();
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });
    AlertDialog alert = builder.create();
    alert.show();
    /*
    if (handleCancel()){
        super.onBackPressed();
    }
    */
}

public void onSuperBackPressed(){
    super.onBackPressed();
}

我刚刚使用onSuperBackPressed - 方法向MyActivity添加了一个新的公共方法super

感谢K_Anas提供了出色的想法。

答案 2 :(得分:5)

  

我在OnBackPressed中创建了AlertDialog并显示它,但是当我按下后退按钮时,应用程序才关闭,我收到错误消息,说窗口正在泄漏。

如果您正在调用OnBackPressed super.OnBackPressed(),那么应用程序将完成,因为这是OnBackPressed的基本实现。不要调用super方法,应用程序也不会关闭。

答案 3 :(得分:0)

在对话框中调用yourActivity.this.onBackPressed()

utility.makeAlertDialog("Cancel Verification","Do you want to cancel the verification process","Cancel Verification",new DialogInterface.OnClickListener(){
        @Override
        public void onClick(DialogInterface dialog, int which) {
            utility.failureToast("OTP verification");
            Intent intent = new Intent(MobileOTPActivity.this,MobileNumberLoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
            MobileOTPActivity.this.onBackPressed();
        }
    },"Close");