0

The counter variable cannot be referred to in the public void onClick(View v) method, since it is defined in a different method. Below is the relevant code.

    Button button;
    final TextView message;
    int counter = 0;

    button = (Button) findViewById(R.id.button5);
    message = (TextView) findViewById(R.id.tv5);

    message.setText("Clicked " + 0 + " times.");

    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            counter++;
            message.setText("Clicked " + counter + " times.");

        }
    });

Are there any ideas as to how to fix this?

The reason I do not want to declare counter as a final variable is because I still want to change its value in the Onclick method.

Thank you.

user2938543
  • 327
  • 1
  • 6
  • 12

1 Answers1

0

As @Raghunandan referred the link Accessing Local Variables of the Enclosing Scope, and Declaring and Accessing Members of the Anonymous Class it's described everything you needs. It's clearly describe that

An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.

Basically click listener is an anonymous class. You can't use local non final variable here. If you want to change the variable scope you have to move it as a class variable. I guess it make sense to you.

androidcodehunter
  • 21,567
  • 19
  • 47
  • 70