一个按钮一分钟内应该只点击两次,应该如何检查?

问题描述 投票:0回答:1

一个按钮在一分钟内只能被点击两次,如果用户在50.秒内第三次被点击,应用程序将通过吐司信息警告用户。如果用户在50秒内第三次点击,应用程序将通过吐司信息警告用户。此外,对于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();
        }
    });
java android timer countdowntimer
1个回答
2
投票

我建议你启动一个计数器,每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;
             }

     }



  }

0
投票

只需保留一个单一的计数器变量。然后使用这段代码,当计数器的值变成2的时候

new Handler().postDelayed(new Runnable() 
{
    public void run() 
    {
        img_number_search.setEnabled(false);
    }
}, 60000    //Specific time in milliseconds

);

这段代码可以让按钮停用1分钟。


0
投票

你可以使用Thread来完成这个任务。

int counter=0; //globally declared

在OnClick方法中

if(counter==0)
{
 Thread th=new Thread(new callthread());
       th.start();
}

counter++;

if(counter<=2)
{
//TODO
}
else
{
Toast.makeText(context, "You can use this property only two times in a minute", Toast.LENGTH_SHORT).show();
        }

调试方法

public class callthread implements Runnable{
    @Override
    public void run() {
        try {
            Thread.sleep(Interval time in millisec);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        counter=0;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.