Skip to content

Instantly share code, notes, and snippets.

@abdalin
Last active April 8, 2018 21:36
Show Gist options
  • Save abdalin/2fbd99cf9f810eff94bf08632cf5cf2f to your computer and use it in GitHub Desktop.
Save abdalin/2fbd99cf9f810eff94bf08632cf5cf2f to your computer and use it in GitHub Desktop.
listener to get notified using LinearSnapHelper with RecyclerView
private void attachSnapHelper(RecyclerView recyclerView, final RecyclerView.LayoutManager layoutManager) {
final SnapHelper snapHelper = new LinearSnapHelper();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
boolean mScrolled = false;
int snapPosition;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE && mScrolled) {
mScrolled = false;
final View currentView = snapHelper.findSnapView(layoutManager);
if (currentView == null) return; // null when layout manager doesn't scroll
int pos = layoutManager.getPosition(currentView);
if (snapPosition != pos) {
snapPosition = pos;
Log.d(TAG, "Snap Pos: " + snapPosition);
}
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dx != 0 || dy != 0) {
mScrolled = true;
}
}
});
snapHelper.attachToRecyclerView(recyclerView);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment