当我按下按钮时,我想让我的对话框保持打开状态。目前它正在关闭。
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
发布于 2013-03-26 00:03:50
我相信@Kamen的答案是正确的,这里是一个使用匿名类的相同方法的示例,所以它都在一个代码流中:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Test for preventing dialog close");
AlertDialog dialog = builder.create();
dialog.show();
//Overriding the handler immediately after show is probably a better approach than OnShowListener as described below
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Boolean wantToCloseDialog = false;
//Do stuff, possibly set wantToCloseDialog to true then...
if(wantToCloseDialog)
dismiss();
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});
我在这里写了一篇更详细的文章来回答同样的问题,其中也有DialogFragment和DialogPreference等其他对话框的例子。
发布于 2017-07-24 16:06:45
您不需要创建自定义类。您可以为AlertDialog注册View.OnClickListener。此监听程序不会关闭AlertDialog。这里的诀窍是,您需要在显示对话框之后注册侦听器,但可以在OnShowListener中巧妙地完成此操作。您可以使用附件布尔变量来检查此操作是否已完成,以便只执行一次:
/*
* Prepare the alert with a Builder.
*/
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setNegativeButton("Button", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {}
});
this.alert = b.create();
/*
* Add an OnShowListener to change the OnClickListener on the
* first time the alert is shown. Calling getButton() before
* the alert is shown will return null. Then use a regular
* View.OnClickListener for the button, which will not
* dismiss the AlertDialog after it has been called.
*/
this.alertReady = false;
alert.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
if (alertReady == false) {
Button button = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//do something
}
});
alertReady = true;
}
}
});
发布于 2011-05-27 01:07:19
您可能需要定义自己的布局,并且不使用“官方”按钮;您所要求的行为不是典型的对话框。
https://stackoverflow.com/questions/6142308
复制相似问题