2017-04-24 242 views
0

我試圖重寫的onkeydown()與onBackPressed()方法,但警告對話框沿着方法,而不是不顯示它只是回到以前的intent.I嘗試幾個例子,但他們都沒有工作。OnBackPressed不顯示警報

@Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
      if (keyCode == KeyEvent.KEYCODE_BACK) { 
     onBackPressed(); 

     } 

     return super.onKeyDown(keyCode, event); 
    } 

     @Override 
     public void onBackPressed() { 


     Log.d("confirm save method",""); 
     AlertDialog.Builder builder = new AlertDialog.Builder(this); 

      builder.setTitle(""); 
      builder.setMessage("Do you want to Save the Game ?"); 
      builder.setCancelable(false); 
       builder.setPositiveButton("YES", 
       new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int which) { 
        finish(); 
        System.exit(0); 
       } 
      }); 

    builder.setNegativeButton("NO", 
      new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
        dialog.cancel(); 
       } 
      }); 

       AlertDialog alert = builder.create(); 
       alert.show(); 


      Log.d("confirm save method",""); 

}

回答

0
@Override 
public void onBackPressed() { 
    AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    builder.setMessage("Are you sure you want to exit?") 
      .setTitle("Exit Alert") 
      .setCancelable(false) 
      .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 

        //finishAffinity(); 
        finish(); //or do anything 
       } 
      }) 
      .setNegativeButton("No", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        dialog.cancel(); 
       } 
      }); 
    AlertDialog alert = builder.create(); 
    alert.show(); 
} 

試試這個代碼,同時還刪除您的onkeydown();

1
  • 提示1:如果重寫onBackPressed,你不必重寫onKeyDown(int keyCode, KeyEvent event)。這很複雜。刪除這個方法(onKeyDown)可以解決這個問題。
  • 提示2:return true中斷此鍵事件。

    @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
         if (keyCode == KeyEvent.KEYCODE_BACK) { 
         alertAialog(); 
         return true; 
         } 
    
        return super.onKeyDown(keyCode, event); 
    } 
    private void alertDialog(){ 
    ... 
    }