Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass an argument when calling setOnClickListener?

Is it possible to pass an argument to the listener when a button is clicked:

protected void onCreate(Bundle savedInstanceState) {
    ....

    String myArg = "Hello";
    Button button1 = (Button)findViewById(R.id.myButton);
    button1.setOnClickListener(myListener);

    String myArg = "Goodye";
    Button button2 = (Button)findViewById(R.id.myOtherButton);
    button2.setOnClickListener(myListener);
}

OnClickListener clickListener = new View.OnClickListener() {

    @Override
    public void onClick(View v) {
            // print the value from the passed in argument myArg
        Log.v("TEST", myArg);           
    }
};

This is just an example and not a reflection on what I actually wan't to do but it does illustrate the question.

Basically I want to pass in myArg to the listener so when the button is clicked it has access to the myArg variable.

I know I could do this as an inline anonymous class but I will have lots of buttons and the click logic is the same for all of them. I need the argument as it will be different for each button.

FYI: My real usage requires that the argument be a View object.

like image 767
Camsoft Avatar asked Dec 21 '22 02:12

Camsoft


2 Answers

I think the typical manner in which this sort of problem is addressed is a test of the id of the click target:

OnClickListener clickListener = new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.myButton) {
             //
        } elseif (v.getId()==R.id.myOtherButton) {
             //
        }       
    }
};

If that's insufficient, you can employ the generic tag property of a view:

Button button1 = (Button)findViewById(R.id.myButton);
button1.setTag("Hello");
button1.setOnClickListener(myListener);

Button button2 = (Button)findViewById(R.id.myOtherButton);
button2.setTag("Goodye");
button2.setOnClickListener(myListener);

...
OnClickListener clickListener = new View.OnClickListener() {

@Override
public void onClick(View v) {
        // print the value from the passed in argument myArg
    Log.v("TEST", v.getTag());           
   }
};

And finally you can even set multiple tags:

 button1.setTag(R.id.arg1, "Hello");
 button1.setTag(R.id.arg2, "World");

Would that suit your purposes?

like image 161
Phillip Fitzsimmons Avatar answered Jan 08 '23 08:01

Phillip Fitzsimmons


Why not just create a class that implements View.OnClickListener? This would ideal if you are reusing the code for each button as well.

public class MyListener implements View.OnClickListener 
{
    private View mView;

    public MyListener(View v) {
        mView = v;
    }

    @Override
    public void onClick(View v) {
        // Use mView here if needed             
    }
}

And then use it like you would normally:

OnClickListener listener = new MyListener(myView);
like image 32
onit Avatar answered Jan 08 '23 07:01

onit