有没有办法在单击中性按钮或否定按钮时覆盖警告对话框的行为,以便不自动关闭。
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Title");
builder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do something and close dialog
}
});
builder.setNeutralButton("Clear All", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do something but not close dialog
}
});
builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which, boolean isChecked) {
if(isChecked){
// do something
} else {
// do something else
}
}
});
final AlertDialog dialog = builder.create();
dialog.show();
此处负面按钮的预期行为是:点击" 全部清除"它应该只清除所有的选择而不是自动关闭对话框。但Android alertDialog会在点击 NegativeButton 或 NeutralButton 时自动关闭对话框。任何覆盖此行为的方法
答案 0 :(得分:1)
所以我能够在dialog.create()之后和dialog.show()
之前添加 dialog.setOnShowListener()来实现这一点。 builder.setNeutralButton("Clear All", null);
builder.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button clearAll = builder.getButton(AlertDialog.BUTTON_NEUTRAL);
clearAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// do something but don't dismiss
for(int which=0; which<checkedItems.length; which++){
((AlertDialog) dialog).getListView().setItemChecked(which, false);
}
}
});
}
});
循环解决了一个问题,问题:单击清除所有时,警告对话框中的复选框UI不会更改。因此,运行最后一个循环来更改UI,使所有复选框都未选中。