2 years ago

#38617

test-img

Shobhit

Android: Disable button, process code and enable button not working

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.

android

android-studio

onclicklistener

android-button

floating-action-button

0 Answers

Your Answer

Accepted video resources