Override dialog onBackPressed()?

2020-02-10 00:17发布

How would I override a Dialog's onBackPressed to close the dialog as well as calling finish() on the Activity it is located in?

5条回答
Melony?
2楼-- · 2020-02-10 00:56
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
  return new Dialog(getActivity(), getTheme()){
    @Override
    public void onBackPressed(){
      // dismiss();
      // activityReference.finish();
    }
  };
}
查看更多
家丑人穷心不美
3楼-- · 2020-02-10 01:04

You can use setOnCancelListener:

dialog.setOnCancelListener(new DialogInterface.OnCancelListener()
{
    @Override
    public void onCancel(DialogInterface dialog)
    {
         MyActivity.this.finish();
    }
});

You need to finish only your activity. Dialog will be dismissed automatically.

查看更多
祖国的老花朵
4楼-- · 2020-02-10 01:15

in my case i use DialogFragment, which is still a dialog.. so i overriden onCancel() in my dialog, and it reacts like onBackPressed() of the Activity everytime i click the back button when dialog is shown.

@Override
public void onCancel(DialogInterface dialog) 
{
    super.onCancel(dialog);
    Log.i("RecDialog.onCancel()", "onCancel");
}

hope i helped.

查看更多
一夜七次
5楼-- · 2020-02-10 01:16

I finally added a key listener to my dialog to listen to the Back key. Not as elegant as overriding onBackPressed() but it works. Here is the code:

dlgDetails = new AlertDialog.Builder(this)
    .setOnKeyListener(new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey (DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && 
                event.getAction() == KeyEvent.ACTION_UP && 
                !event.isCanceled()) {
                dialog.cancel();
                showDialog(DIALOG_MENU);
                return true;
            }
            return false;
        }
    })
    //(Rest of the .stuff ...)
查看更多
Viruses.
6楼-- · 2020-02-10 01:19
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_BACK) {
                               dialog.cancel();
                               return true;
                            }
                         return false;
                    }
                })
查看更多
登录 后发表回答