带有警告对话框的Android退出按钮

jan*_*ana 1 android exit android-alertdialog

我使用以下代码退出我的应用程序.

Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

现在,当我按下退出键时,它应显示警告对话框.如果我按下确定,关闭应用程序否则不.

Xar*_*mer 14

删除super.OnBackPressed()

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you want to exit?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    MyActivity.this.finish();
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });
    AlertDialog alert = builder.create();
    alert.show();

}
Run Code Online (Sandbox Code Playgroud)