Reputation: 1496
How to prevent user from doing multiple clicks on a button??.
Actual problem: if user keep clicking on the button very quickly. Button click execute my api call multiple times.
Applied Solution Not Work: Even if you tried to disable the button directly after onClick(), still there is a probability to have multiple click happened.
Upvotes: 7
Views: 4106
Reputation: 114
//its work same as setOnClickListener
//Create Function Like this in Utils File
fun View.setOnclick(listenerBlock: OnDebounceClickListener) =
setOnClickListener(MulticlickPrevent(1000L, listenerBlock))
interface OnDebounceClickListener {
fun onClick(view: View?)
}
class MulticlickPrevent(
private val interval: Long,
private val listenerBlock: OnDebounceClickListener
) : View.OnClickListener {
private var LastClickListner = 0L
override fun onClick(v: View) {
val time = System.currentTimeMillis()
if (time - LastClickListner >= interval) {
LastClickListner = time
listenerBlock.onClick(v)
}
}
}
//On activity use like this
myview.setOnclick(object : OnDebClickListener{
override fun onClick(var1: View?) {
TODO("Do your code")
}
})
//Or
class MainActivity : Activity() , OnDebClickListener{
//in onCreate method
myview.setOnclick(this)
}
Upvotes: 0
Reputation: 566
You can achieve the task using below code:
var mLastClickTime = 0L
fun isClickRecently(): Boolean {
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
return true
}
mLastClickTime = SystemClock.elapsedRealtime()
return false
}
And you can call this function on button click.
button.setOnClickListener {
if (!isClickRecently()) {
//your task to do
}
}
Upvotes: 1
Reputation: 1496
Solving Android multiple clicks problem — Kotlin
I searched the community and found amazing solution like creating a custom click listener that will preserve the last click time and prevent clicking for a specific period But — as a big fan of Kotlin — I was thinking to have something to use very smoothly using the power of lambdas and closures. So I came up with this implementation, hope to help you
Step 1 : Create class with name SafeClickListener.kt
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)
}
}
Step 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)
}
Step 3 : Now it is very easy to use it. Just replace button1.setonclicklistner with setSafeOnClickListener.
settingsButton.setSafeOnClickListener {
showSettingsScreen()
}
Upvotes: 18