Toast display when the button is pressed frequently

I am new to Android development, so excuse me for this question.

So, I have a button that, when clicked, will call a method called btnDelay(btnName).

Inside this method is this line of codes:

private void btnDelay(final Button btn){
    btn.setEnabled(false);

    /*if (counter == 0){
        counter++;
    }*/

    Timer buttonTimer = new Timer();
    buttonTimer.schedule(new TimerTask() {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    btn.setEnabled(true);
                }
            });
        }
    }, 5000);
}

This will disable the button for 5 seconds .

Now what I want to do is when the user presses the button again and does not end for 5 seconds, displays Toast, which indicates that the user’s action is too frequent.

Is there a way I can do this? I am thinking of using a counter that will count how many times the user clicked this particular button and will reset to 0 after 5 seconds in TimerTask. But is there an easier way to do this? Thank.

+4
2

onClick, . , , - , , onClick :

if(enabled){
  btnDelay();
} 
else {
  sendAToast();
}

btnDelay() enabled = false ( , ), run() enabled = true. private boolean enabled = true :)

+5

. , btn.setEnabled(false);, buttonClickEvent .

boolean btnState = true;
private void btnDelay(final Button btn){
    if (btnState){
        Timer buttonTimer = new Timer();
        buttonTimer.schedule(new TimerTask() {

            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btnState = false;
                    }
                });
            }
        }, 5000);
    }else{
        Toast.makeText(this, "your_message", Toast.LENGTH_SHORT).show();
    }
}
+1

Source: https://habr.com/ru/post/1692212/


All Articles