How to pass parameters to OnClickListener?
How can i pass parameter to an OnClickListener() ?
Got my Listener:
OnClickListener myListener = new OnClickListener()
{
@Override
public void onClick(View v)
{
//I want to reach params here
}
};
I got 12 buttons and i dont want to write 12 listeners for them, it would be great to just pass a string to them and they can do completly different things.
Use your own custom OnClickListener
public class MyLovelyOnClickListener implements OnClickListener
{
int myLovelyVariable;
public MyLovelyOnClickListener(int myLovelyVariable) {
this.myLovelyVariable = myLovelyVariable;
}
@Override
public void onClick(View v)
{
//read your lovely variable
}
};
Another solution for that issue, you can create a regular method and pass to it the View
you want to add the onClickListener
to it, and pass the parameters you want to use along with it:
Button b1 = new Button();
String something = "something";
Button b2 = new Button();
String anotherSomething = "anotherSomething";
setOnClick(b1, something);
setOnClick(b2, anotherSomething);
private void setOnClick(final Button btn, final String str){
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Do whatever you want(str can be used here)
}
});
}