开发者

Differentiate single Dialogs with DialogInterface.OnClickListener

开发者 https://www.devze.com 2023-04-10 22:00 出处:网络
We have two AlertDialog objects AlertDialog dialog1, dialog2; both dialogs are created via AlertDialog.Builder.

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 DialogIn开发者_开发知识库terface.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 your dialogs have differentiable content, you can obviously tell the dialog directly by its content:

if(which==AlertDialog.BUTTON_NEGATIVE)return;
AlertDialog theDialog = (AlertDialog)dialog;
if(theDialog.findViewById(R.id.phoneinput)!=null) ...;//handle the phone
if(theDialog.findViewById(R.id.emailinput)!=null) ...;//handle the email

Of course the solution is NOT universal, but quite handy in some cases.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号