for (int i = 0; i < 9; i++)
{
b[i].setOnClickListener(
new OnClickListener()
{
public void onClick(View v)
{
justclicked(i);
}
}
);
}
I am attempting to put an action listener on nine buttons using a for loop. The code above is giving me an error. Is the error caused by the value of i not being visible? Thanks a lot, world-class experts @ Stack Overflow!!
No, it's because i isn't final, which it must be to access from an anonymous inner class.
Add
final int finalI = i;
before
b[i].setOnClickListener( ...
and then use finalI instead of i: justclicked(finalI);.
After that, think up a better name for i and finalI.
Create a class that implements OnClickListener with i as a constructor argument and use that to set the listeners.
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