How to increase the counter inside the OnClick viewing event

I know this may seem very simple, but here is my problem:

I have an onclickevent listener that should infinitely increment the counter on click:

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

The problem is that I cannot call the counter from inside the onclick event if it is not set to final . However, since it is final, I can no longer change its value.

I tried to place the counter in the onclick event, i.e.:

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

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

? , , onclick, , , . onclick , reset , .

+3
3

:

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

"counter" Activity oncreate.

+1
    t.setOnClickListener(new View.OnClickListener() {
        int Counter = 0;
        @Override
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), R.string.hey, Toast.LENGTH_SHORT).show();
            t.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
            c.setBackgroundColor(getResources().getColor(R.color.colorAccent));
            p.setVisibility(View.VISIBLE);
            if (Counter >= 0) {
                Counter++;
                e.setText("you clicked Click me "+Counter +"number of times");
                e.setTextSize(15);
                e.setTextColor(getResources().getColor(R.color.colorPrimary));
                e.setSingleLine();
            }
0

Source: https://habr.com/ru/post/1773375/


All Articles