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 star
You can Disable the view temporarily like this
public static void disableTemporarly(final View view) {
view.setEnabled(false);
view.post(new Runnable() {
@Override
public void run() {
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
class SafeClickListener(
private var defaultInterval: Int = 1000,
private val onSafeCLick: (View) -> Unit
) : View.OnClickListener {
private var lastTimeClicked: Long = 0
override fun onClick(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 ;)