Using a loop to set onclicklistener buttons

I try to use a loop to set the action for each button when I click (since most buttons just return their text value), however I get an error message in which the "variable" I "accesses from inside the inner class must 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; } 
+5
source share
3 answers

You can copy the value of i to the final variable temp 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 } } }); } 
+8
source

You create an anonymous class ( View.OnClickListener ) for each button, the onClick() method in this class has a different scope than the getValuesPressed() method, so it does not have access to the local variable i .

The solution is in the link above:

An anonymous class cannot access local variables in its application that are not declared final or actually final.

Therefore, introducing the final variable into the loop would eliminate the error:

 String getValuesPressed(){ for(int i = 0; i < buttonList.length; i++){ final int j = i; buttonList[i].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(j == 0){//error occurs here //do stuff } } }); } return textOnScreen; } 
+2
source

You can create your own listener that takes a position as a parameter to get around the fact that you are using an anonymous inner class.

 private class MyClickListener implements View.OnClickListener { int position; public MyClickListener (int position) { this.position = position; } @Override public void onClick(View v) { if(position == 0){ //do stuff } } } 

Then in your loop you can create it like this:

 String getValuesPressed(){ for(int i = 0; i < buttonList.length; i++){ buttonList[i].setOnClickListener(new MyClickListener(i)); } return textOnScreen; } 
+1
source

All Articles