Last active
August 18, 2023 04:48
-
-
Save DanielKnauf/98bde791e13af55ce420587acb6866c4 to your computer and use it in GitHub Desktop.
OnItemTouchListener blocking MotionEvent from RecyclerViews' parent if RecyclerView can scroll left or right
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
addOnItemTouchListener( | |
object : RecyclerView.OnItemTouchListener { | |
private var startX = 0f | |
override fun onInterceptTouchEvent( | |
recyclerView: RecyclerView, | |
event: MotionEvent | |
): Boolean = | |
when (event.action) { | |
MotionEvent.ACTION_DOWN -> { startX = event.x } | |
MotionEvent.ACTION_MOVE -> { | |
val isScrollingRight = event.x < startX | |
val scrollItemsToRight = isScrollingRight && recyclerView.canScrollRight | |
val scrollItemsToLeft = !isScrollingRight && recyclerView.canScrollLeft | |
val disallowIntercept = scrollItemsToRight || scrollItemsToLeft | |
recyclerView.parent.requestDisallowInterceptTouchEvent(disallowIntercept) | |
} | |
MotionEvent.ACTION_UP -> { startX = 0f } | |
else -> Unit | |
}.let { false } | |
override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) = Unit | |
override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) = Unit | |
} | |
) | |
private val RecyclerView.canScrollRight: Boolean | |
get() = canScrollHorizontally(SCROLL_DIRECTION_RIGHT) | |
private val RecyclerView.canScrollLeft: Boolean | |
get() = canScrollHorizontally(SCROLL_DIRECTION_LEFT) | |
private const val SCROLL_DIRECTION_RIGHT = 1 | |
private const val SCROLL_DIRECTION_LEFT = -1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment