Stuyvenstein
Stuyvenstein

Reputation: 2447

Android AlertDialog in onClickListener get parent View

I have an onClickListener event containing an AlertDialog with an onClick event, I want to get the parent onClick events view, example:

View.OnClickListener listener = new View.OnClickListener(){
    public void onClick(View v){
        //need to pass v to alert's onClickListener
        AlertDialog.Builder alert = new AlertDialog.Builder(MyClass.this);
        alert.setPositiveButton("Go", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog,int which){
                //need parent onClick's View as v
                String str = v.getTag().toString();
                Toast.makeText(getApplicationContext(),str,Toast.LENGTH_SHORT).show();
            }
        });
    }
};

Any idea how to achieve this? I can't call (View)findViewById(id) inside the onclicklistener because this will be applied to multiple items created programmatically

Upvotes: 3

Views: 6528

Answers (2)

Zeev G
Zeev G

Reputation: 2211

you forgot to call

alert.show();

without this the dialog will not be displayed

full source code:

    someViewItem.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(final View v) {


                AlertDialog.Builder alert = new AlertDialog.Builder(MyActivity.this);
                alert.setMessage("abcd");
                alert.setPositiveButton("Go",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {

                                String str = "aaa";
                                Toast.makeText(getApplicationContext(),
                                        str, Toast.LENGTH_SHORT).show();
                            }
                        });
                alert.show();


            }
        });

Upvotes: 0

toadzky
toadzky

Reputation: 3846

change

public void onClick(View v)

to

public void onClick(final View v)

This will let you access the clicked view inside the dialog button's onClickListener.

Upvotes: 7

Related Questions