简体   繁体   中英

Display a Toast when a button is clicked frequently

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

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

Inside that 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);
}

That will disable the button for 5 seconds .

Now what I want to do is when the user clicks the button again and the 5 seconds is not finished, will display a Toast stating 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 that specific button and will reset to 0 after the 5 seconds on the TimerTask is done. But is there a simplier way to do that? Thank you.

Your button won't fire an onClick event if it's disabled. So instead of disabling it, set the colours to grey or something so it looks disabled and then in your onClick handler for the button:

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

Then in btnDelay() , set enabled = false (and set the colours to grey if you want), and inside run() set enabled = true . Also don't forget to private boolean enabled = true at the top of your class :)

You should declare a Boolean variable for button state. Because if you write btn.setEnabled(false); , buttonClickEvent can not be triggered for five seconds.

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM