We have two AlertDialog
objects
AlertDialog dialog1, dialog2;
both dialogs are created via AlertDialog.Builder
.
How can we recognize which dialog is source of event in DialogInterface.OnClickListener
?
with single dialog we can do this:
AlertDialogInstance.setOnClickListener(myListener);
//myListener
public void onClick(DialogInterface arg0, int arg1) {
switch (arg1) {
case AlertDialog.BUTTON_NEGATIVE:
// do something
break;
case AlertDialog.BUTTON_POSITIVE:
// do something
break;
case AlertDialog.BUTTON_NEUTRAL:
// do something
break;
}
}
how to modify this switch
logic to handle multiple dialogs?
(Or if there is better system to handle dialogs, other than inline button callbacks, what is it?)
I'll recommend you to put needed param in the custom listener.
private class CustomOnClickListener implements OnClickListener {
private int id;
public CustomOnClickListener(int id) {
this.id = id;
}
public void onClick(DialogInterface dialog, int which) {
//check id and which
}
}
Then, when you add onClickListeners to dialogs, you just provide an id to listener.
private AlertDialog dialog1;
private AlertDialog dialog1;
@Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
dialog1 = new AlertDialog.Builder(this).setTitle("dialog1").create();
dialog1.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", this);
dialog2 = new AlertDialog.Builder(this).setTitle("dialog2").create();
dialog2.setButton(AlertDialog.BUTTON_NEGATIVE, "NO", this);
}
@Override
public void onClick(final DialogInterface dialog, final int which)
{
if (dialog == dialog1)
{
if (which == AlertDialog.BUTTON_POSITIVE)
{
//
}
else if (which == AlertDialog.BUTTON_NEGATIVE)
{
//
}
}
else if (dialog == dialog2)
{
if (which == AlertDialog.BUTTON_POSITIVE)
{
//
}
else if (which == AlertDialog.BUTTON_NEGATIVE)
{
//
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With