android studio中退出时弹出对话框

在app中总是不小心点击了退出怎么办?当然是加个弹出的提示框了,本人新手,就加在主界面上了

 @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AlertDialog.Builder bdr=new AlertDialog.Builder(this);
            bdr.setMessage("确定要退出XX助手吗?");
            bdr.setIcon(R.drawable.ic_book_white_24dp);
            bdr.setNegativeButton("退出",this);
            bdr.setPositiveButton("取消",this);
            bdr.show();
            return  true;
        }
        return super.onKeyDown(keyCode, event);
    }

  

 @Override
    public void onClick(DialogInterface dialog, int which) {
        //处理退出对话框的事项.
        if (which==DialogInterface.BUTTON_POSITIVE){

        }
        if (which==DialogInterface.BUTTON_NEGATIVE){
            finish();
        }
    }

然后运行在模拟器上后一点击退出键,就app无响应挂掉了,很是无语,不知什么原因,但是在真机上能正常运行.

原文地址:https://www.cnblogs.com/wjbych/p/7161024.html