后退按钮的监听器

Listener for BACK-button

当显示警告对话框时,我如何才能对后退按钮执行任何操作? 我必须问用户 "Do you really want discard changes?"

此时屏幕上出现输入提示对话框

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

@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

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
                    }

                }
            });