1

我有一个对话框显示,我希望在按下后退按钮时要求用户确认他想在取消生效之前取消对话框。这是我的代码:

dialog.setOnCancelListener(new OnCancelListener(){

            @Override
            public void onCancel(DialogInterface arg0) {
                AlertDialog.Builder builder = new AlertDialog.Builder(dialog.getContext());
                builder.setMessage( "Are you sure you want to cancel?")
                       .setCancelable(false)
                       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface diag, int id) {
                               diag.dismiss();
                               dialog.dismiss();

                           }
                       })
                       .setNegativeButton("No", new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface diag, int id) {
                                diag.cancel();
                           }
                       });
                AlertDialog alert = builder.create();
                alert.show();               
            }

        });
        dialog.show();

问题是,当按下后退按钮时,我当前的对话框被取消,然后显示我的“确认消息”。如何确保在用户确认之前不会取消对话框?

4

2 回答 2

6

onCancel取消对话时调用,这就是取消对话后显示确认消息的原因。你应该setOnKeyListener代替你的对话。

dialog.setOnKeyListener(new OnKeyListener() {
    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Toast.makeText(Activity.this, "back pressed", Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }
});
于 2012-10-03T02:36:13.050 回答
0

您可以像这样自定义基本对话框:

private void doCreateBaseDlg(){
    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.activity_dialog_on_dialog_cutomize);
    dialog.setTitle("Title...");

    //this is the button in your customize layout
    Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
    dialogButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            doCreate1stDlg();//here display your second conform dialog
        }
    });

    dialog.show();
}

我试过了,效果很好。希望能帮到你。

于 2012-10-03T02:55:15.263 回答