1

I want complete code to disable a Button for some time for example 2 minutes in Android Studio. Thank you for help.

 protected void onclick(View v){

    bwasta = (Button) findViewById(R.id.btDes);
    new CountDownTimer(10000, 10) { //Set Timer for 10 seconds
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            bwasta.setEnabled(true);
            bwasta.setEnabled(false);
        }
    }.start();
Uncle Iroh
  • 5,748
  • 6
  • 48
  • 61
zhiwa
  • 21
  • 1
  • 2

3 Answers3

1

This might help you out.

Button bwasta = (Button) findViewById(R.id.btDes);

bwasta.setEnabled(false);

new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                Thread.sleep(2*
                             60*
                            1000);//min secs millisecs
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            YourActivityName.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    bwasta.setEnabled(true);

                }
            });
        }
    }).start();
Sachin Bahukhandi
  • 2,378
  • 20
  • 29
1

DO NOT RELY ON Thread.sleep()

Actually, there is already a Question and an Answer on SO regarding the inaccuracy of Thread.sleep()(as per the OP's experience) here.

The answer then favors the accuracy of a ScheduledThreadPoolExecutor using the schedule() method.

Do the following:

Button bwasta = (Button) findViewById(R.id.btDes);

bwasta.setEnabled(false);

ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.schedule(new new Runnable() {

    @Override
    public void run() {

        YourActivityName.this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                bwasta.setEnabled(true);

            }
        });
    }
}, 2, TimeUnit.MINUTES);
Community
  • 1
  • 1
Manish Kumar Sharma
  • 12,982
  • 9
  • 58
  • 105
0

You can use mHandler.postDelayed(mRunnable, mTime) function to achieve this

Button bwasta = (Button) findViewById(R.id.btDes);

bwasta.setEnabled(false);

bwasta.postDelayed(new Runnable() {
  public void run() {
    bwasta.setEnabled(true);
  }
}, 2*60*1000);
chiru
  • 635
  • 1
  • 7
  • 14