Hi,
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 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.)
Thanks for your help! Steve
PS: Sorry if this question goes up twice; the page appeared to freeze the first time I tried posting.