Domanda

for example:

for (int i = 0; i < 10; i++){
   SomeClass something = new SomeClass();
   something.setOnClickListener(new OnClickListener() {
      public void onClick(){
         doSomething(i);
      }
   });
}

I am not allowed to use the variable i, Eclipse suggest me make the i final, but I cannot do that because I need it to iterate right?

È stato utile?

Soluzione

Copy i to a final variable in the loop body.

for (int i = 0; i < 10; i++){
   final int j = i;
   SomeClass something = new SomeClass();
   something.setOnClickListener(new OnClickListener() {
      public void onClick(){
         doSomething(j);
      }
   });
}

Altri suggerimenti

You can do

loop with i
  final int k = i
  annonymousClass
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top