How to pass parameters to OnClickListener?
I know this is a late answer but hopefully it can help someone. None of the existing answers worked in my situation but I ended up using the setTag feature of an image that was acting like a button. My account info was in a global member variable that was set up when the activity started.
In this case I am setting up a table with each row being an account. The account details are shown when the image is clicked (the image is just an info icon).
Thus:
// prior code....
// NOTE: oneAccount is an object (AccountInfo) holding information about the account
// column with the "detail" arrow
image1 = new ImageView(this);
image1.setImageResource(R.drawable.info);
image1.setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
image1.setPadding(15, 1, 15, 1);
image1.setTag(oneAccount);
// add a listener to go to that account detail on a click
image1.setOnClickListener(new TextView.OnClickListener() {
public void onClick(View v) {
// change the color to signify a click
v.setBackgroundColor(getResources().getColor(R.color.button_selected));
// get what we need out of the tag
AccountInfo thisAcct = (AccountInfo) v.getTag();
// your code would do other stuff here
}
});
// add the image to the table row
tr1.addView(image1);
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)
}
});
}
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
}
};