Passing a variable's value not reference in an OnClickListener()
<p>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.</p>

<p>That's probably not very clear - here's the code:</p>

<pre><code>for (int i = 0; i &lt; 20; i++) {
    cells[i] = (ImageView) findViewById(cellIDs[i]);
    cells[cellnumber++].setOnClickListener(new OnClickListener() {
    public void onClick(View v){
          cellClicked(cellnumber, v);
       }
    });
}
</code></pre>

<p>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?</p>

<p>(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.)</p>

<p>Thanks for your help!
Steve</p>

<p>PS: Sorry if this question goes up twice; the page appeared to freeze the first time I tried posting.</p>
