Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a loop to set the buttons onclicklistener

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;
}
like image 294
mr nooby noob Avatar asked Aug 08 '15 09:08

mr nooby noob


1 Answers

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
                }
            }
        });
    }
like image 142
Sanjeet A Avatar answered Oct 13 '22 01:10

Sanjeet A