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.
Why not just create a class that implements View.OnClickListener? This would ideal if you are reusing the code for each button as well.
And then use it like you would normally: