How To Prevent Double Code Running By Clicking Twice Fast To A Button In Android
If i click fast to my button in my Android app, it seems that code behind it runs twice. If i click my menu button twice the activity that has to be launch onclick just starts twic
Solution 1:
You can use following code: btn.setEnabled(false);
btn.setOnclickListener(newView.onClickListener(){
publicvoidonClick(View v) {
btn.setEnabled(false);
}
});
Solution 2:
You can Disable the view temporarily like this
publicstaticvoiddisableTemporarly(final View view) {
view.setEnabled(false);
view.post(newRunnable() {
@Overridepublicvoidrun() {
view.setEnabled(true);
}
});
}
Edit:
The above solution will work fine. But it will become even better when using the power of Kotlin
1) Create the SafeClikc Listener
classSafeClickListener(
privatevar defaultInterval: Int = 1000,
privateval onSafeCLick: (View) -> Unit
) : View.OnClickListener {
privatevar lastTimeClicked: Long = 0overridefunonClick(v: View) {
if (SystemClock.elapsedRealtime() - lastTimeClicked < defaultInterval) {
return
}
lastTimeClicked = SystemClock.elapsedRealtime()
onSafeCLick(v)
}
}
2) Add extension function to make it works with any view, this will create a new SafeClickListener and delegate the work to it
fun View.setSafeOnClickListener(onSafeClick: (View) -> Unit) {
val safeClickListener = SafeClickListener {
onSafeClick(it)
}
setOnClickListener(safeClickListener)
}
3) Now it is very easy to use it
settingsButton.setSafeOnClickListener {
showSettingsScreen()
}
Happy Kotlin ;)
Solution 3:
Button.setOnClickListener(newView.OnClickListener {
@OverridepublicvoidonClick(final View v) {
v.setEnabled(false);
v.postDelayed(newRunnable() {
@Overridepublicvoidrun() {
v.setEnabled(true);
}
},150); //150 is in milliseconds
}
});
Solution 4:
Well, that's the expected behaviour...
Launch your new acvitity with SINGLE_TOP flag
Or try setting android:launchMode="singleInstance"
for Top20 activity in your AndroidManifest.xml
Solution 5:
This solves the issue of multiple Instances of activity, and still play the default animation
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Post a Comment for "How To Prevent Double Code Running By Clicking Twice Fast To A Button In Android"