2014-01-20 34 views
0

如何在DialogInterface.OnClickListner正面按鈕中執行後退命令?我想首先詢問用戶他/她是否想要回到之前的活動。我試過super.onBackPressed();,但它不是一個有效的代碼。 這裏是我的代碼:Android中的對話框界面中的軟鍵代碼行

@Override 
    public void onBackPressed(){ 

    DialogInterface.OnClickListener confirm = new DialogInterface.OnClickListener() { 

     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      // TODO Auto-generated method stub 
      switch(which){ 
      case DialogInterface.BUTTON_POSITIVE:{ 
       //execute back function 
       super.onBackPressed(); 
       break; 
      } 
      case DialogInterface.BUTTON_NEGATIVE:{ 
       //Do nothing, just stay on the current activity 
      } 

      } 
     } 
    }; 
    AlertDialog.Builder msgbox = new AlertDialog.Builder(this); 
    msgbox.setMessage("Are you sure you want to go back?"); 
    msgbox.setPositiveButton("Yes", confirm); 
    msgbox.setNegativeButton("No", confirm); 
    msgbox.show(); 
} 

super.onBackPressed();是給我這個錯誤提示The method onBackPressed() is undefined for the type object

回答

1

OK,我已經修改了代碼,以滿足您的需求。這應該做的。

@Override 
    public void onBackPressed(){ 

    DialogInterface.OnClickListener confirm = new DialogInterface.OnClickListener() { 

     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      // TODO Auto-generated method stub 
      switch(which){ 
      case DialogInterface.BUTTON_POSITIVE:{ 
       //execute back function 
       finish(); 
       break; 
      } 
      case DialogInterface.BUTTON_NEGATIVE:{ 
       //Do nothing, just stay on the current activity 
       break; 
      } 

      } 
     } 
    }; 
    AlertDialog.Builder msgbox = new AlertDialog.Builder(this); 
    msgbox.setMessage("Are you sure you want to go back?"); 
    msgbox.setPositiveButton("Yes", confirm); 
    msgbox.setNegativeButton("No", confirm); 
    msgbox.show(); 
} 
+0

我還會在你給出的這段代碼的頂部使用'@Override public void onBackPressed(){}'嗎? @tgo –

+0

不,刪除'@Override public void onBackPressed(){}'並把我放在 – TGO

+0

之上的覆蓋處理我按鈕點擊的代碼在'onBackPressed();'本身。我還可以在哪裏放置我的'DialogInterface.OnClickListener'? –

相關問題