Search code examples
androidandroid-layout

Disable button after a click for 2 seconds and resume back


When I click a resend button first time, the button will disable for 2 seconds.After 2 seconds the button will enable? I am using this code

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            btn.setEnabled(false);
            btn.postDelayed(new Runnable() {
                public void run() {
                    btn.setEnabled(true);
                    Log.d(TAG,"resend1");
                }
            },1000);
        }
    });

But this code is not working properly.


Solution

  • try this for this purpose you can use Handler(import android.os.Handler;)

      btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            btn.setEnabled(false);
    
         new Handler().postDelayed(new Runnable() {
    
            @Override
            public void run() {
                // This method will be executed once the timer is over
                    btn.setEnabled(true);
                    Log.d(TAG,"resend1");
    
            }
        },2000);// set time as per your requirement 
        }
    });