Here are my actions in onClick(). The problem is that if I press the button twice, the new activity will be opened twice. I tried to use setEnabled() and setClickable(), but it does not work. It still shows more then one activity
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),
CalendarActivity.class);
intent.putExtra("day", 16);
intent.putExtra("month", 12);
intent.putExtra("year", 1996);
startActivityForResult(intent, CALENDAR_ACTIVITY_CODE);
}
});
This is actually a surprisingly complex problem. The root of the issue is that UI events (e.g. a button click) cause messages to be "posted" to the end of a message queue. If you are fast enough, it's possible to get many of these messages posted to the message queue before the first one is ever processed.
This means that even disabling the button inside your onClick()
method won't truly solve the problem (since the disabling won't "happen" until the first message is processed, but you might already have three other duplicate messages waiting in the message queue).
The best thing to do is to track some sort of boolean flag and check the flag every time inside onClick()
:
private boolean firstClick = true;
button.setOnClickListener(v -> {
if (firstClick) {
firstClick = false;
// do your stuff
}
});
You have to remember to reset firstClick
back to true whenever you want to re-enable button taps, of course.