Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a Counter inside an OnClick View Event

Tags:

android

sdk

I know this might sound very basic but here's my problem:

I have an onclickevent listener that's supposed to increment the counter indefinitely when it's clicked:

final int counter = 0;
myimageView2.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        counter ++;
    }
});

The problem is that I can't seem to call the counter from inside the onclick event unless it's set to final. However since it's final I can no longer change its value either.

I tried placing the counter within the onclick event, i.e.:

myimageView2.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        int counter = 0;
        counter ++;
    }
});

However, clicking it also resets the counter back to zero.

How do I solve this? I want to continuously increment the counter each time I click it, but I can't define the counter outside of the onclick unless it's final, which means I can no longer increment it. And I can't define the counter inside the onclick either since it will only reset its value each time I click it.

like image 429
locke Avatar asked Dec 09 '22 13:12

locke


2 Answers

Solved:

myimageView2.setOnClickListener(new OnClickListener() {
    int counter = 0;
    public void onClick(View v) {
        counter ++;
    }
});
like image 151
locke Avatar answered Dec 30 '22 07:12

locke


You could declare 'counter' outside the Activity's oncreate method.

like image 20
Susheel Avatar answered Dec 30 '22 05:12

Susheel