Last active
August 5, 2025 07:14
-
-
Save ricknout/343c2fead6c9658fd815b96562976f6d to your computer and use it in GitHub Desktop.
Change order of args to enable trailing lambda syntax
This file contains hidden or 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
| package com.nickrout.snaphelperlistener | |
| import androidx.recyclerview.widget.RecyclerView | |
| import androidx.recyclerview.widget.SnapHelper | |
| class SnapOnScrollListener( | |
| private val snapHelper: SnapHelper, | |
| var behavior: Behavior = Behavior.NOTIFY_ON_SCROLL, | |
| var onSnapPositionChangeListener: OnSnapPositionChangeListener? = null | |
| ) : RecyclerView.OnScrollListener() { | |
| enum class Behavior { | |
| NOTIFY_ON_SCROLL, | |
| NOTIFY_ON_SCROLL_STATE_IDLE | |
| } | |
| private var snapPosition = RecyclerView.NO_POSITION | |
| override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { | |
| if (behavior == Behavior.NOTIFY_ON_SCROLL) { | |
| maybeNotifySnapPositionChange(recyclerView) | |
| } | |
| } | |
| override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { | |
| if (behavior == Behavior.NOTIFY_ON_SCROLL_STATE_IDLE | |
| && newState == RecyclerView.SCROLL_STATE_IDLE) { | |
| maybeNotifySnapPositionChange(recyclerView) | |
| } | |
| } | |
| private fun maybeNotifySnapPositionChange(recyclerView: RecyclerView) { | |
| val snapPosition = snapHelper.getSnapPosition(recyclerView) | |
| val snapPositionChanged = this.snapPosition != snapPosition | |
| if (snapPositionChanged) { | |
| onSnapPositionChangeListener?.onSnapPositionChange(snapPosition) | |
| this.snapPosition = snapPosition | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@ricknout
Thanks your code :)
Can I use your code in my commercial app?
Please let me know how I can use the code for commercial distribution.