вы можете использовать пользовательские RecyclerView.OnScrollListener
и findSnapView
для этого, выполнив функцию расширения на SnapHelper
fun SnapHelper.getSnapPosition(recyclerView: RecyclerView): Int {
val layoutManager = recyclerView.layoutManager ?: return RecyclerView.NO_POSITION
val snapView = findSnapView(layoutManager) ?: return RecyclerView.NO_POSITION
return layoutManager.getPosition(snapView)
}
, вот полный код
создать интерфейс длябыть в качестве обратного вызова
interface OnSnapPositionChangeListener {
fun onSnapPositionChange(position: Int)
}
переопределить RecyclerView.OnScrollListener()
class SnapOnScrollListener(private var mSnapHelper: SnapHelper, private var mOnSnapPositionChangeListener: OnSnapPositionChangeListener) : RecyclerView.OnScrollListener() {
private var snapPosition = RecyclerView.NO_POSITION
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
val snapPosition = mSnapHelper.getSnapPosition(recyclerView)
val snapPositionChanged = this.snapPosition != snapPosition && snapPosition != RecyclerView.NO_POSITION
if (snapPositionChanged) {
mOnSnapPositionChangeListener
.onSnapPositionChange(snapPosition)
this.snapPosition = snapPosition
}
}
}
var helper = LinearSnapHelper()
recyclerview.onFlingListener = null
helper.attachToRecyclerView(recyclerview)
recyclerview.addOnScrollListener( SnapOnScrollListener(helper, object : OnSnapPositionChangeListener {
override fun onSnapPositionChange(position: Int) {
//your code
}
}))