I’m trying to set up a large number OnClickListeners through a for loop. Each view should run a method when clicked; view 0 should run the method with the value 0, view 1 with the value 1, etc.
However, if I declare the OnClickListener using a variable which increments through the for loops, the OnClickListener remembers the reference to the variable rather than the value of the variable at the time it was declared.
That’s probably not very clear — here’s the code:
for (int i = 0; i < 20; i++) {
cells[i] = (ImageView) findViewById(cellIDs[i]);
cells[cellnumber++].setOnClickListener(new OnClickListener() {
public void onClick(View v){
cellClicked(cellnumber, v);
}
});
}
That correctly sets up the OnClickListeners for each cell, but whichever one is clicked, it always runs calls cellClicked with value of 21.
I know I can manually set up the OnClickListeners using cell[0] . . . cellClicked(0, v), but is there a way to do it so that the ClickListener is passed the value of the variable rather than a reference to the variable in the for loop?
(I saw a few pages which said that Java normally operates with passing values and not references, but I assume the Android libraries somehow do it differently and hence my difficulties here.)
There’s nothing “special” about the Java semantics in Android.
cellClickedisn’t actually called when you create each listener, andcellnumberisn’t local to the anonymous class you’re creating each time, so each listener is referring to the same variable and thus gets the same value.Use the
View.setTag()method to attach the cell ID to eachView. Then you only need one instance of the listener which, in itsonClickmethod, callsv.getTag()to get the cell ID.Edit:
Here’s some wholly untested code. I don’t actually know off the top of my head if you can cast a boxed Integer like that. Anyway, it’s a start: