Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It appears integer variable i is not visible

Tags:

java

android

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!!

like image 258
user979431 Avatar asked Sep 09 '26 22:09

user979431


2 Answers

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.

like image 93
Ryan Stewart Avatar answered Sep 12 '26 12:09

Ryan Stewart


Create a class that implements OnClickListener with i as a constructor argument and use that to set the listeners.

like image 20
Manfred Moser Avatar answered Sep 12 '26 12:09

Manfred Moser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!