如何在OnClick View事件中增加计数器 [英] How to increment a Counter inside an OnClick View Event

查看:113
本文介绍了如何在OnClick View事件中增加计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这听起来很基础,但这是我的问题:

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

我有一个onclickevent侦听器,该监听器应该在单击时无限期递增计数器:

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 ++;
    }
});

问题在于,除非将onclick事件设置为 final ,否则我似乎无法从onclick事件中调用该计数器.但是,由于它是最终的,所以我也无法再更改其值.

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.

我尝试将计数器放在onclick事件中,即:

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.

我该如何解决?我想每次点击计数器都会不断增加它的数量, 但是除非最后一次,否则我无法在onclick之外定义计数器,这意味着我无法再对其进行递增.而且我也无法在onclick内定义计数器,因为它只会在每次单击时重置其值.

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.

推荐答案

已解决:

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

这篇关于如何在OnClick View事件中增加计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆