2015-09-05 47 views
0

我試圖讓菜單按鈕顯示此消息「你確定要退出應用程序嗎?」有兩個按鈕是和不是。安卓菜單按鈕顯示對話框,確認退出應用程序

我做了這個代碼,但我得到這個錯誤信息:無法訪問的代碼

這裏是我的代碼:

public boolean onOptionsItemSelected(MenuItem paramMenuItem) 
    { 
    switch (paramMenuItem.getItemId()) 
    { 
    default: 
     return super.onOptionsItemSelected(paramMenuItem); 
    } 
    new AlertDialog.Builder(this).setMessage("re you sure you want to exite the app?").setPositiveButton("yes", new DialogInterface.OnClickListener() 
    { 
     public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt) 
     { 
     System.exit(0); 
     } 
    }).setNegativeButton("no", new DialogInterface.OnClickListener() 
    { 
     public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt) {} 
    }).show(); 
    return true; 
    } 

回答

1

你的switch語句是不正確的。

switch (item.getItemId()) { 
     case R.id.action_add: 
      //your code 
      return true; 
     case R.id.action_settings: 
      //your code 
      return true; 
     default: 
      return false; 
    } 

所以,這樣的事情:

public boolean onOptionsItemSelected(MenuItem paramMenuItem) { 
    switch (paramMenuItem.getItemId()) { 
     case R.id.action_exit: 
      showExitDialog(); 
      return true; 
     default: 
      return super.onOptionsItemSelected(paramMenuItem); 
    } 
} 

private void showExitDialog() { 
    new AlertDialog.Builder(this).setMessage("Are you sure you want to exite the app?") 
     .setPositiveButton("yes", new DialogInterface.OnClickListener() 
     { 
      public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt) { 
       System.exit(0); 
      } 
     }) 
     .setNegativeButton("no", new DialogInterface.OnClickListener() 
     { 
      public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt) { 
      } 
     }) 
     .show(); 
} 

和菜單

<?xml version="1.0" encoding="utf-8"?> 
<menu xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto"> 
    <item 
     android:id="@+id/action_exit" 
     app:showAsAction="never"<!--or always if needed--> 
     android:title="Exit"/> 
</menu> 
+0

謝謝,我會試試看。 – user3206753

+0

@ user3206753沒問題。我更新了我的答案。只要替換你的代碼,它應該可以工作。 – kolombo

+0

非常感謝它有效100% – user3206753

相關問題