首页 > 解决方案 > 一个按钮应该在一分钟内只点击两次,我应该如何检查它?

问题描述

一个按钮应该在一分钟内只被点击两次。如果用户第三次点击,例如在 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();
        }
    });

标签: javaandroidtimercountdowntimer

解决方案


我建议您启动一个每 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;
             }

     }



  }

推荐阅读