2016-08-29 215 views
0

我需要在用戶按Back Button時向用戶顯示Alert Message。 我寫了下面的代碼,它顯示Alert Box一秒鐘,然後重定向。我指定ButtonAlert Box,如果用戶clickyes,那麼我創建Intent,否則我希望用戶留在當前活動。如何在按下後退按鈕時顯示警報消息?

現在它顯示我以下錯誤消息。

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(); 
+0

卸下super.onBackPressed();從onBackPressed方法 –

+0

謝謝!讓我試試這個 – Kirmani88

回答

2

評論這個行:

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(); 
相關問題