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:
for (int i = 0; i < button.length; i++) {
for (int j = 0; j < button[0].length; j++) {
button[i][j].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
press(i, j);
}
});
}
}
where press(int i, int j)
is implemented elsewhere. I get the error, "Cannot refer to a non-final variable i inside an inner class defined in a different method".
So, right now I just have each function written out, like this:
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...
This works, but it seems silly. Is there a better way?
Yes, try this:
for (int i = 0; i < button.length; i++) {
for (int j = 0; j < button[0].length; j++) {
final int listenerI = i;
final int listenerJ = j;
button[i][j].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
press(listenerI, listenerJ);
}
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With