应用程序应按下后退按钮提示

时间:2012-12-18 08:35:14

标签: android

我正在开发一个Android应用程序。我希望当我在我的应用程序中按下后退按钮时,它应该给我一个提示(某种警告对话框),如果我真的想退出。 我不知道在哪里放置此警报对话框以及在Yes按钮中写入的内容,用户想要退出应用程序。请帮帮我。

5 个答案:

答案 0 :(得分:8)

您可以覆盖OnBackPressed()功能。

  @Override
public void onBackPressed()
{
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Exit");
    builder.setMessage("Are You Sure?");

    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finish();
            }
        });

    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}

答案 1 :(得分:3)

@Override
public void onBackPressed() {

AlertDialog.Builder alertDialog = new AlertDialog.Builder(
        AppDemoActivity.this);

alertDialog.setPositiveButton("Yes", new OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
        finish();
    }
});

alertDialog.setNegativeButton("No", null);

alertDialog.setMessage("Do you want to exit?");
alertDialog.setTitle("AppTitle");
alertDialog.show();
}

使用此选项可在背面按下时显示警告

答案 2 :(得分:2)

这是覆盖后退按钮的另一种方法:

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Toast.makeText(getApplicationContext(), "Back Pressed", Toast.LENGTH_LONG).show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

感谢。

答案 3 :(得分:1)

您可以覆盖onBackPressed以显示提醒,并在yes按钮finish中覆盖活动..

public void onBackPressed() {
    //show alert here
}

答案 4 :(得分:1)

@Override
    private void onBackPressed() {

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("Do you really want to exit?");
alertDialogBuilder
        .setMessage("Click yes to exit!")
        .setCancelable(false)
        .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {
                // if this button is clicked, close
                // current activity
                ThisActivity.this.finish();
            }
          })
        .setNegativeButton("No",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {
                // if this button is clicked, just close
                // the dialog box and do nothing
                dialog.cancel();
            }
        });             
        AlertDialog alertDialog = alertDialogBuilder.create(); 
        alertDialog.show();
  }