android 菜单按钮显示对话框以确认退出应用程序

android menu button display dialog to confirm exiting from the app

我正在尝试让菜单按钮显示此消息 "are you sure you want to exite the app?" 有两个按钮是和否。

我编写了此代码,但收到此错误消息:无法访问的代码

这是我的代码:

  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;
  }

您的 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>