Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to refer to a non-final variable inside an inner class defined in a different method

Tags:

java

android

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?

like image 394
BenH Avatar asked Dec 10 '22 02:12

BenH


1 Answers

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);
            }
        });
    }
}
like image 182
Vojislav Stojkovic Avatar answered Jan 21 '23 10:01

Vojislav Stojkovic