I have a button in my activity. When the user clicks on the button, progress is shown and a request is sent to the server, after receiving a response to the request, the progress is hided and the next activity is opened. However, if the user has time to press the button several times, two or more activities will open. For preventing double click I use DebouncedOnClickListener. Here is my code:
abstract class DebouncedOnClickListener protected constructor() : View.OnClickListener {
private val minimumIntervalMillis: Long = 1000
private val lastClickMap: MutableMap<View, Long>
abstract fun onDebouncedClick(v: View?)
override fun onClick(clickedView: View) {
val previousClickTimestamp = lastClickMap[clickedView]
val currentTimestamp = SystemClock.uptimeMillis()
lastClickMap[clickedView] = currentTimestamp
if (previousClickTimestamp == null || abs(currentTimestamp - previousClickTimestamp) > minimumIntervalMillis) {
onDebouncedClick(clickedView)
}
}
init {
lastClickMap = WeakHashMap()
}
}
This method works in many cases. However, the request can be processed for an unknown amount of time. And the user can click on the button while the request is completed, the progress will be closed and the process of opening the next activity will start. I do not know how long a new activity can be launched, and at this moment another click on the button can occur, which will subsequently lead to the opening of two activities.
How can you avoid double clicking until the activity opens, please help me.
P.S. Even when I try to disable the button, double-clicking can still happen during the launch of the activity
CodePudding user response:
Just paste this on button click
button.setEnabled(false);
CodePudding user response:
You can use a boolean flag like following.
private val onClicked: Boolean = false
override fun onClick(clickedView: View) {
if(!onClicked) {
onClicked = true
// Do something
onClicked = false
}
}
CodePudding user response:
Add required functions in Utils and wherever it's required call it by passing view as parameter.
const val DIGIT_THOUSAND = 1000
fun preventMultipleTap(view: View) {
preventMultipleTap(view, DIGIT_THOUSAND.toLong())
}
fun preventMultipleTap(view: View, delayInMillis: Long) {
view.isEnabled = false
view.postDelayed({ view.isEnabled = true }, delayInMillis)
}