我有一个对话框显示,我希望在按下后退按钮时要求用户确认他要在取消生效前取消对话框。这是我的代码:
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();
问题是当按下后退按钮时,我的当前对话框被取消,然后显示我的“确认消息”。在用户确认对话框之前,如何确保不会取消对话框?
答案 0 :(得分: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;
}
});
答案 1 :(得分: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();
}
我试过了,它运行正常。希望可以帮到你。