Skip to content

Instantly share code, notes, and snippets.

@eleddie
Created June 26, 2017 00:04
Show Gist options
  • Save eleddie/30b73fa3e91a33931461e93dded2f4ee to your computer and use it in GitHub Desktop.
Save eleddie/30b73fa3e91a33931461e93dded2f4ee to your computer and use it in GitHub Desktop.
Class to handle single tap and long press on the RecyclerView in Android using Kotlin
class RecyclerTouchListener(context: Context, recyclerView: RecyclerView, val clickListener: ClickListener) : RecyclerView.OnItemTouchListener {
val gestureDetector: GestureDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapUp(e: MotionEvent?): Boolean = true
override fun onLongPress(e: MotionEvent) {
val child: View? = recyclerView.findChildViewUnder(e.x, e.y)
if (child != null)
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child).toLong())
super.onLongPress(e)
}
})
override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
val child: View? = rv.findChildViewUnder(e.x, e.y)
if (child != null && gestureDetector.onTouchEvent(e))
clickListener.onClick(child, rv.getChildAdapterPosition(child).toLong())
return false
}
override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {}
override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {}
interface ClickListener {
fun onClick(view: View, position: Long)
fun onLongClick(view: View, position: Long)
}
}
@eleddie
Copy link
Author

eleddie commented Jun 26, 2017

To use it, add the listener to the RecyclerView as follows:

list.addOnItemTouchListener(RecyclerTouchListener(this, list, object : RecyclerTouchListener.ClickListener {
    override fun onClick(view: View, position: Long) {
        Log.i("onClick", "Position $position")
    }

    override fun onLongClick(view: View, position: Long) {
        Log.i("onLongClick", "Position $position")
    }
}))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment