Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiate single Dialogs with DialogInterface.OnClickListener

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?)

like image 428
Marek Sebera Avatar asked Oct 03 '11 14:10

Marek Sebera


2 Answers

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.

like image 169
QuickNick Avatar answered Sep 18 '22 11:09

QuickNick


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)
        {
            //
        }
    }
}
like image 38
jakk Avatar answered Sep 20 '22 11:09

jakk