0

I am developing an android app where I have a Floating Action Button (or Button). Upon clicking this button, it should first disable itself, followed by a heavy task and then enable itself. The idea is, the user should not be able to click on the button until unless the task is ongoing.

Current code looks like:

public class MainActivity extends AppCompatActivity {
    private FloatingActionButton dummyButton;
 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        dummyButton = findViewById(R.id.dummyButton);

        dummyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                v.setEnabled(false); //or v.setClickable(false); or dummyButton.setEnabled(false); or dummyButton.setClickable(false);

                //some example code that takes upto 8seconds
                try {
                    Thread.sleep(8000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                v.setEnabled(true); //or v.setClickable(true); or dummyButton.setEnabled(true); or dummyButton.setClickable(true);
            }
        });
    }
}

The above code somehow does not work as expected. While the process is ongoing, the user is still able to click the button n times. All the n clicks stacks up the onClickListener events which is executed one after the other.

I am not sure where am I going wrong. Any kind of help/idea is appreciated. Thanks in advance.

Shobhit
  • 407
  • 5
  • 15
  • Does your code actually have `Thread.sleep` or you put it just to make an example? It's not recommended sleeping on the UI Thread. – Nicola Fanelli Jan 11 '22 at 18:08
  • @Nicola: The actual code does not have `Thread.sleep`. It is just an example to reflect the idea. – Shobhit Jan 12 '22 at 09:04
  • In that case I think that maybe the code doesn't take so much time and that the button gets enabled almost instantly. If you need to make it disabled for a certain amount of time you could look a [this](https://stackoverflow.com/q/29198262/10902946). – Nicola Fanelli Jan 12 '22 at 09:45

0 Answers0