java - 一个按钮应该在一分钟内只点击两次,我应该如何检查它?
问题描述
一个按钮应该在一分钟内只被点击两次。如果用户第三次点击,例如在 50. second 中,应用程序将通过 toast 消息警告用户。此外,对于 4. 和 2. 点击也应该有 60 秒。我试图为此编写一个方法,
int counter = 0;
long counterOne = 0;
long counterTwo = 0;
long counterThree = 0;
private boolean checkTime() {
counter++;
if (counter == 1) {
counterOne = System.currentTimeMillis();
}
if (counter == 2) {
counterTwo = System.currentTimeMillis();
}
if (counter == 3) {
counterThree = System.currentTimeMillis();
}
if (counterThree != 0) {
if (counterThree < (counterOne + (60 * 1000))) {
counter--;
return false;
}
}
if (counter == 1 || counter == 2 || counterThree > (counterOne + (60 * 1000))) {
if (counter == 3) {
counter = 1;
counterOne = counterThree;
}
return true;
}
return false;
}
我想把它用作;
img_number_search.setOnClickListener(view -> {
if (checkTime()) {
// TODO
}
else {
Toast.makeText(context, "You can use this property only two times in a minute", Toast.LENGTH_SHORT).show();
}
});
解决方案
我建议您启动一个每 60 秒重置一次的计数器。
尝试这样的事情:
private int counter=0;
private Long timeSinceLastClick = 0;
private boolean checkTime(){
if(counter == 0){
timeSinceLastClicked = System.currentTimeMillis;
} // if our counter is zero, we start a timer.
counter++;
if(counter < 2){ // if our counter is less than two , then we return true.
return true;
}else{ // Otherwise we need to check if 60 seconds passed.
long currentTime = System.currentTimeMillis();
long timeDifference = (currentTime-timeSinceLastClick)/1000;
if(timeDifference > 60){ // been more than 60 seconds.
counter =0;
timeSinceLastClicked = System.currentTimeMillis;
counter++;
return true;
}else{
return false;
}
}
}
推荐阅读
- reactjs - 从 React.js 中的状态数组呈现特定值
- android - 返回结果和lateinit:属性执行尚未初始化
- reactjs - 关于功能性 React 最佳实践的建议
- datatable - 如何添加下载到我的应用程序的功能
- javascript - VM101:1 未捕获的语法错误:JSON.parse 中位置 0 处的 JSON 中的意外标记 <
) 在 XMLHttpRequest.xhr.onload (app.js:134) - eclipse - 在 Eclipse 上使用来自 SVN 的单独源文件夹
- java - 错误:“未提供名称属性”- 用于 log4j2.properties 自定义
- r - 重叠散点图、线穿过散点图和密度图
- wcf - 在本地使用证书测试 WCF 服务
- sql-server - 是否可以从 CSV 文件同时生成 FMT 和表格?