Reputation: 2104
Is there a way to override the behavior of alert dialog box on clicking of neutral button or negative button to not auto dismiss .
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();
The expected behavior of negative button here is : on clicking of "Clear All" it should just clear the selection that's all and not automatically close the dialog.? But Android alertDialog automatically closes the dialog, on click of NegativeButton or NeutralButton. Any way to override this behavior
Upvotes: 1
Views: 1002
Reputation: 2104
So i was able to achieve this with adding dialog.setOnShowListener() after dialog.create() and before dialog.show()
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);
}
}
});
}
});
Loop solves one problem, Problem: on clicking clear all, the checkbox UI in alert dialog doesn't change. So run a final loop to change the UI, making all checkbox unchecked.
Upvotes: 1