Reputation: 73
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
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
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
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
Reputation: 805
Why not use setOnAction
?
newPostBtn.setOnAction(e -> {
(your logic goes here)
newPostBtn.setEnabled(false);
}) ;
Upvotes: 2
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