Last active
April 8, 2018 21:36
-
-
Save abdalin/2fbd99cf9f810eff94bf08632cf5cf2f to your computer and use it in GitHub Desktop.
listener to get notified using LinearSnapHelper with RecyclerView
This file contains 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
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