BACK-button的监听器

时间:2016-05-02 16:45:24

标签: android back

显示警告对话框时,如何获取后退按钮的操作? 我不得不问用户"你真的想要丢弃变更吗?"

此时屏幕上有输入警告对话框。

2 个答案:

答案 0 :(得分:1)

你最初的问题并不是很清楚你想做什么。因此,如果您希望在用户在EditText中输入内容后按下后退按钮时显示对话框,则需要在Activity类中@Override onBackPressed方法。

@Override
public void onBackPressed() {
    // Here you want to show the user a dialog box
    new AlertDialog.Builder(context)
        .setTitle("Exiting the App")
        .setMessage("Are you sure?")
        .setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                // The user wants to leave - so dismiss the dialog and exit
                 finish();
                 dialog.dismiss();
            }
        }).setNegativeButton("NO", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                // The user is not sure, so you can exit or just stay 
                dialog.dismiss();
            }
        }).show();

}

您可以查看已接受的答案here

但是如果你只想按下对话框本身的后退按钮,那么这个问题已经有了答案 - 基本上你在对话框上设置OnKeyListener就像这样:

dialog.setOnKeyListener(new Dialog.OnKeyListener() {

      @Override
      public boolean onKey(DialogInterface arg0, int keyCode,KeyEvent event)
      {
         if (keyCode == KeyEvent.KEYCODE_BACK) {
               /* The user pressed back button - do whatever here.
               Normally you dismiss the dialog like dialog.dismiss(); */

             }
            return true;
            }
        });

查看已接受的答案here

答案 1 :(得分:0)

builder.setNegativeButton(R.string.btn_rev, new DialogInterface.OnClickListener(){
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //если что-то ввели и нажали Назад
                    if (edText.getText() != null) {
                       // onBackPressed(); //here's code for back-button
                    }

                }
            });