Alexandre Gagné
Alexandre Gagné

Reputation: 73

Prevent double click on OnClickListener

I tried to prevent the user from clicking on my button twice. I tried to use setEnabled on my script but nothing happens! My problems are, I tried to do this in setOnClickListener.

Can someone please help me to find a solution to prevent clicking while everything is being uploaded to the server?

newPostBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // I want to set my button to enabled false here
    }
}

Upvotes: 3

Views: 2201

Answers (5)

Bunny
Bunny

Reputation: 1064

You can also try setClickable

In Android, a widget that is not clickable will not respond to click events

view.setClickable(false);

newPostBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        v.setClickable(false);

// I want to set my button to enabled false here
}}

Upvotes: 0

Akshay Paliwal
Akshay Paliwal

Reputation: 3916

Sometimes next screens/actions takes time to be executed and frequent taps or clicks on view performs that next screen/action multiple times. I resolved this issue by counting time between two clicks. Please find code example below:

button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // mis-clicking prevention, using threshold of 1000 ms
        if (SystemClock.elapsedRealtime() - mLastClickTime < 1000){
            return;
        }
        mLastClickTime = SystemClock.elapsedRealtime();

        // do your action here
    }
}

Upvotes: 0

Sunny
Sunny

Reputation: 3265

Below are the three ways to fix this:

Disable the button with setEnabled(false) until it is safe for the user to click it again.

Above given solution is also a way to fix it.

Another solution is

private long lastClickTime = 0;

View.OnClickListener buttonHandler = new View.OnClickListener() {
    public void onClick(View v) {
        // preventing double, using threshold of 1000 ms
        if (SystemClock.elapsedRealtime() - lastClickTime < 1000){
            return;
        }

        lastClickTime = SystemClock.elapsedRealtime();
    }
}

Upvotes: 0

bakero98
bakero98

Reputation: 805

Why not use setOnAction?

newPostBtn.setOnAction(e -> {
    (your logic goes here)

    newPostBtn.setEnabled(false);
}) ;

Upvotes: 2

Paris B. G.
Paris B. G.

Reputation: 394

1) make an instance variable:

 private int buttonClicks;

2) instantiate your variable in onCreate

 buttonClicks = 0;

3) set if() statement in onClickListener

newPostBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) { 
            if (buttonClicks == 1){
               buttonClicks = 0;
               //do nothing
               } else {

                //run code
                }
                   buttonClicks++;

Upvotes: 2

Related Questions