Java 如何计算Android中按钮的点击次数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27755327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to count number of Button clicks in Android
提问by Carole Mattar
i'm building an android application and I need to count how many times a button is clicked within a specific time the display it in another page, any help?
我正在构建一个 android 应用程序,我需要计算在特定时间内单击按钮的次数并将其显示在另一个页面上,有什么帮助吗?
回答by sandipon
try this way, first declare global variable on your activity class file like below :
尝试这种方式,首先在您的活动类文件上声明全局变量,如下所示:
int clickcount=0;
after add click event to button and increment value clickcount variable like below code:
将单击事件添加到按钮并增加值 clickcount 变量后,如下代码所示:
yourbutton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
clickcount=clickcount+1;
if(clickcount==1)
{
//first time clicked to do this
Toast.makeText(getApplicationContext(),"Button clicked first time!", Toast.LENGTH_LONG).show();
}
else
{
//check how many times clicked and so on
Toast.makeText(getApplicationContext(),"Button clicked count is"+clickcount, Toast.LENGTH_LONG).show();
}
}
});
回答by SomeSome
you can add clicks into List<Long/*timestamp*/>
and read values later, you can store your clicks into list and cleanup this list by timer. you can... you have many ways to do this. and save values into your database or preferences, if you need.
您可以List<Long/*timestamp*/>
稍后添加点击并读取值,您可以将点击存储到列表中并通过计时器清理此列表。你可以......你有很多方法可以做到这一点。并根据需要将值保存到您的数据库或首选项中。
回答by Ojonugwa Jude Ochalifu
The answer given by @sandipon is fine.But global variables could be destroyed,you can use SharedPreferences to store the value in case you'd like to make it persistent.
@sandipon 给出的答案很好。但是全局变量可能会被破坏,如果您想让它持久化,您可以使用 SharedPreferences 来存储该值。