Created
June 26, 2017 00:04
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use it, add the listener to the RecyclerView as follows: