Android - How to prevent multiple view clicks using DataBinding and Kotlin extensions

How to prevent the users from clicking the view multiple times

M.I.
1 min readApr 13, 2019

“How to prevent the users from clicking the view multiple times”

We sometimes encountered this problem.

So I’d like to share the solution using Kotlin extensions and DataBinding library, while keep code changes to a minimum as far as possible.

Sample app

1.Add setOnSingleClickListener function and OnSingleClickListener class.

2. Set single click listener in layout xml using app:onSingleClick

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<data>

<variable
name="clickListener"
type="android.view.View.OnClickListener"/>
</data>

<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

~~~

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SingleClickButton"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/hw"
app:onSingleClick="@{clickListener}"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

Or call setOnSingleClickListener programmatically

button.setOnSingleClickListener(View.OnClickListener {
// TODO handle click action.

})

Or set OnSingleClickListener for View#setOnClickListener method.

button.setOnClickListener(OnSingleClickListener(View.OnClickListener {
// TODO handle click action.
}
, intervalMs = 3000))

--

--