按下后退按钮时如何显示警报消息?

时间:2016-08-29 14:18:08

标签: android android-layout android-fragments alertdialog

每当他按下Alert Message时,我都需要向用户显示Back Button。 我编写了以下代码,它显示Alert Box一秒钟,然后重定向。我在Button中指定了Alert Box,如果click上有用户yes,那么我创建了Intent,否则我希望用户留在当前活动中。< / p>

现在它显示以下错误消息。

android.view.WindowLeaked: Activity checkout.Checkout has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{100e8093 V.E..... R.....I. 0,0-1080,476} that was originally added here
             at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
             at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:271)
             at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
             at android.app.Dialog.show(Dialog.java:298)
             at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:953)

代码。

@Override
public void onBackPressed() {
    super.onBackPressed();

    AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(this);
    alertDialog2.setTitle("Delete Data");
    alertDialog2.setMessage("Are you sure you want to go back?.");
    // Add the buttons
    alertDialog2.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // User clicked OK button
            //Here i am doing JSON Stuff
            JSONObject commandData = new JSONObject(); 

        }
    });
    alertDialog2.show();

2 个答案:

答案 0 :(得分:2)

评论此行:

super.onBackPressed();

答案 1 :(得分:2)

@Override
public void onBackPressed() {

    AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(this);
    alertDialog2.setTitle("Delete Data");
    alertDialog2.setMessage("Are you sure you want to go back?.");
    // Add the buttons
    alertDialog2.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // User clicked OK button
            //Here i am doing JSON Stuff
            JSONObject commandData = new JSONObject(); 

        }
    });

   alertDialog2.setNegativeButton("No",new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
          YourClass.super.onBackPressed();

        }
    };
    alertDialog2.show();