I want to refer to a non-final variable inside an inner class defined in a different method
<p>I'm writing an Android app, in which I have several buttons laid out in a grid.  I want to set the onClick method of each button, so I wrote this:</p>

<pre><code>for (int i = 0; i &lt; button.length; i++) {
    for (int j = 0; j &lt; button[0].length; j++) {
        button[i][j].setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                press(i, j);
            }
        });
    }
}
</code></pre>

<p>where <code>press(int i, int j)</code> is implemented elsewhere.  I get the error, "Cannot refer to a non-final variable i inside an inner class defined in a different method".</p>

<p>So, right now I just have each function written out, like this:</p>

<pre><code>button[0][0].setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        press(0, 0);
    }
});

button[0][1].setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        press(0, 1);
    }
});

// more like this...
</code></pre>

<p>This works, but it seems silly.  Is there a better way?</p>
