In this post, I’ll show you how we can write double tap listener in android. For doing that I’ll create one demo project and will implement it. So Lets started
Write a DoubleClickListener
Create an abstract class named is DoubleClickListener which extends native View.OnClickListener. Technically nothing we are doing. Simply observe the normal click If the second click happens with delta time then we triggered onDoubleClick event. Just like below
package com.doubletaplistener import android.view.View abstract class DoubleClickListener : View.OnClickListener { private var lastClickTime: Long = 0 override fun onClick(v: View) { val clickTime = System.currentTimeMillis() if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA) { onDoubleClick(v) lastClickTime = 0 } lastClickTime = clickTime } abstract fun onDoubleClick(v: View) companion object { private const val DOUBLE_CLICK_TIME_DELTA: Long = 300 //milliseconds } }
Lets come to the implementation
For implementation double tap listener just create an android sample project. You can apply double click listener is anywhere. In this demo, I’m taking one button. On this button, I will set double click listener, for verifying this I’ll show the toast.
package com.doubletaplistener import android.os.Bundle import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // handle double tap event doubleTap.setOnClickListener(object : DoubleClickListener() { override fun onDoubleClick(v: View) { Toast.makeText(applicationContext,"Double Clicked Attempts",Toast.LENGTH_SHORT).show() } }) } }
Conclusion
In this android app Example, I show you Double Tap Listener Android Example. I hope it’s helpful for you, then help me by sharing this post with all your friends who learning android app development.
1 Comment
Thanks for the help!