I am trying to use a loop to set the action for each button when clicked (since most of the buttons will just return their text value), however I am getting an error stating "variable 'i' is accessed from within inner class, needs to be declared final". How can I get around this?
Here is what I got
String getValuesPressed(){
    for(int i = 0; i < buttonList.length; i++){
        buttonList[i].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(i == 0){//error occurs here
                    //do stuff
                }
            }
        });
    }
    return textOnScreen;
}
                You can copy the value of i in to a temp final variable as -
for (int i = 0; i < buttonList.length; i++) {
        final int finalI = i;
        buttonList[i].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (finalI == 0) {//error occurs here
                    //do stuff
                }
            }
        });
    }
                        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