简体   繁体   English

BACK按钮的监听器

[英]Listener for BACK-button

How I can get any action for back-button when the alert dialog is shown? 显示警报对话框时,如何对后退按钮执行任何操作? I have to ask user "Do you really want discard changes?" 我必须问用户“您真的要放弃更改吗?”

At this time there is alert dialog for input on the screen. 此时,屏幕上将显示警报对话框以供输入。

Your initial question was not very clear on what you wanted to do. 您最初的问题不是很清楚您想做什么。 So if you want to show a dialog when a user presses the back button after having types something in the EditText - then you need to @Override the onBackPressed method in your Activity class. 所以,如果你想要在用户有类型的东西在后按下后退按钮,显示一个对话框EditText -那么你需要@OverrideonBackPressed方法在你的Activity类。

@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();

}

You can look at the accepted answer here . 您可以在此处查看已接受的答案。

But if you only wanted to handle the back-button press on the Dialog itself, then there's already an answer for this question - basically you set an OnKeyListener on the dialog like this: 但是,如果您只想处理Dialog本身上的后退按钮,则该问题已经有了答案-基本上,您OnKeyListener在对话框上设置如下所示的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;
            }
        });

Look at the accepted answer 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
                    }

                }
            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM