ANDROID: How to put a delay after a button is pushed?

前端 未结 3 791
你的背包
你的背包 2021-01-02 02:32

I have a button and when it is pressed it plays an audio file. I want to put a 5 second delay on the button so users wont mash the button and play the sound over and over. I

相关标签:
3条回答
  • 2021-01-02 03:08

    In your onClickListener for the button:

    myButton.setEnabled(false);
    
    Timer buttonTimer = new Timer();
    buttonTimer.schedule(new TimerTask() {
    
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
    
                @Override
                public void run() {
                    myButton.setEnabled(true);
                }
            });
        }
    }, 5000);
    

    This will disable the button when clicked, and enable it again after 5 seconds.

    If the click event is handled in a class that extends View rather than in an Activity do the same thing but replace runOnUiThread with post.

    0 讨论(0)
  • 2021-01-02 03:09

    You can disable your button, then use the postDelayed method on your button.

    myButton.setEnabled(false);
    myButton.postDelayed(new Runnable() {
        @Override
        public void run() {
            myButton.setEnabled(true);
        }
    }, 5000);
    

    This is similar to the Timer solution, but it might better handle configuration change (for example if the user rotate the phone)

    0 讨论(0)
  • 2021-01-02 03:10

    Here you go.

    ((Button) findViewById(R.id.click))
        .setOnClickListener(new OnClickListener() {
    
        @Override
        public void onClick(View v) {
            ((Button) findViewById(R.id.click)).setEnabled(false);
    
            new Handler().postDelayed(new Runnable() {
    
                @Override
                public void run() {
                    ((Button) findViewById(R.id.click))
                        .setEnabled(true);
    
                }
            }, 5000);
    
        }
    });
    
    0 讨论(0)
提交回复
热议问题