How to display Alert Message when back button is Pressed?

痴心易碎 提交于 2019-12-13 07:07:29

问题


I need to display an Alert Message to the user whenever he pressed Back Button. I have written following code, it displays Alert Box for a second and then redirect. I have specified Button in Alert Box, If user click on yes, then i create Intent, else i want user to stay on the current activity.

Right now it displays me following error message.

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)

Code.

@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();

回答1:


Comment this line:

super.onBackPressed();



回答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();


来源:https://stackoverflow.com/questions/39208509/how-to-display-alert-message-when-back-button-is-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!