这是一种验证输入并在输入无效时在屏幕上保留警告对话框的方法。实际上,它删除了对话框并创建了一个新副本。
在您的 setPostiveButton 的 onClick 函数中,进行验证。如果事情不是他们应该的样子,向用户展示一个 Toast。然后在您的对话框上调用 removeDialog 。然后 - 这是棘手的部分,在您的对话框上异步调用 showDialog(如果适用,使用 args)。另外:为了不丢失用户的输入,您应该将他们输入的值放入您调用对话框的包中。当然,您的对话框设置代码需要在包中查找这些值并适当地预填充对话框字段。
所以你的代码看起来像这样:
alert.setPositiveButton(id,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
if ((your validation conditions)) {
// validation conditions not satisfied
removeDialog(myDialogId);
Toast.makeText(blah blah).show();
// now create a new args bundle for the dialog
Bundle newArgs = new Bundle();
// now copy whatever you need from the args used to invoke to dialog
newArgs.putIntegerArrayList("items", myList);
// now save the user's input in a bundle
newArgs.putString("dialogToFieldContent", toString);
final Bundle finalArgs = newArgs;
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
showDialog(myDialogId, finalArgs);
}
});
}
else {
// if everything is ok
}
}
});