Guest User

Untitled

a guest
Aug 28th, 2020
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. package seri.dnair.utils
  2.  
  3. import android.content.Context
  4. import android.util.AttributeSet
  5. import android.view.MotionEvent
  6. import androidx.recyclerview.widget.RecyclerView
  7.  
  8. /**
  9. * A RecyclerView that only handles scroll events with the same orientation of its LayoutManager.
  10. * Avoids situations where nested recyclerviews don't receive touch events properly:
  11. */
  12. class OrientationAwareRecyclerView @JvmOverloads constructor(
  13. context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
  14. ) : RecyclerView(context, attrs, defStyleAttr) {
  15. private var lastX = 0.0f
  16. private var lastY = 0.0f
  17. private var scrolling = false
  18. override fun onInterceptTouchEvent(e: MotionEvent): Boolean {
  19. val lm = layoutManager ?: return super.onInterceptTouchEvent(e)
  20. var allowScroll = true
  21. when (e.actionMasked) {
  22. MotionEvent.ACTION_DOWN -> {
  23. lastX = e.x
  24. lastY = e.y
  25. // If we were scrolling, stop now by faking a touch release
  26. if (scrolling) {
  27. val newEvent = MotionEvent.obtain(e)
  28. newEvent.action = MotionEvent.ACTION_UP
  29. return super.onInterceptTouchEvent(newEvent)
  30. }
  31. }
  32. MotionEvent.ACTION_MOVE -> {
  33.  
  34. // We're moving, so check if we're trying
  35. // to scroll vertically or horizontally so we don't intercept the wrong event.
  36. val currentX = e.x
  37. val currentY = e.y
  38. val dx = Math.abs(currentX - lastX)
  39. val dy = Math.abs(currentY - lastY)
  40. allowScroll = if (dy > dx) lm.canScrollVertically() else lm.canScrollHorizontally()
  41. }
  42. }
  43. return if (!allowScroll) {
  44. false
  45. }
  46. else super.onInterceptTouchEvent(e)
  47. }
  48.  
  49. init {
  50. addOnScrollListener(object : OnScrollListener() {
  51. override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
  52. super.onScrollStateChanged(recyclerView, newState)
  53. scrolling = newState != SCROLL_STATE_IDLE
  54. }
  55. })
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment