Skip to content

Instantly share code, notes, and snippets.

@Veeyikpong
Created July 31, 2019 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Veeyikpong/aec06cfaf66dfcad427a47654953cd7d to your computer and use it in GitHub Desktop.
Save Veeyikpong/aec06cfaf66dfcad427a47654953cd7d to your computer and use it in GitHub Desktop.
A nested horizontal recyclerview to achieves smooth horizontal scrolling. Written in Kotlin.
package com.veeyikpong.utils
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.abs
class NestedHorizontalRecyclerView : RecyclerView {
private val Y_BUFFER = 10
private var preX = 0f
private var preY = 0f
constructor(context: Context) : this(context, null){
addOnItemTouchListener()
}
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0){
addOnItemTouchListener()
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr){
addOnItemTouchListener()
}
private fun addOnItemTouchListener(){
this.addOnItemTouchListener(object: OnItemTouchListener {
override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {
}
override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
}
override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
when (e.action) {
MotionEvent.ACTION_DOWN -> rv.parent.requestDisallowInterceptTouchEvent(true)
MotionEvent.ACTION_MOVE -> {
if (abs(e.x - preX) > abs(e.y - preY)) {
rv.parent.requestDisallowInterceptTouchEvent(true)
} else if (abs(e.y - preY) > Y_BUFFER) {
rv.parent.requestDisallowInterceptTouchEvent(false)
}
}
}
preX = e.x
preY = e.y
return false
}
})
}
}
@Veeyikpong
Copy link
Author

Sample usage

Just use this component as your normal recyclerview in XML like this:

<com.veeyikpong.utils.NestedHorizontalRecyclerView
           android:id="@+id/recyclerView"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content
/>

And you are good to go!

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