Created
May 27, 2019 13:11
-
-
Save caneryilmaz/da8f717b7f848c42bb781410ba2d2fa2 to your computer and use it in GitHub Desktop.
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
pagerView.setOnScrollListener(new RecyclerView.OnScrollListener() { | |
private boolean scrollingUp; | |
@Override | |
public void onScrolled(RecyclerView recyclerView, int dx, int dy) { | |
// Or use dx for horizontal scrolling | |
scrollingUp = dy < 0; | |
} | |
@Override | |
public void onScrollStateChanged(RecyclerView recyclerView, int newState) { | |
// Make sure scrolling has stopped before snapping | |
if (newState == RecyclerView.SCROLL_STATE_IDLE) { | |
// layoutManager is the recyclerview's layout manager which you need to have reference in advance | |
int visiblePosition = scrollingUp ? layoutManager.findFirstVisibleItemPosition() | |
: layoutManager.findLastVisibleItemPosition(); | |
int completelyVisiblePosition = scrollingUp ? layoutManager | |
.findFirstCompletelyVisibleItemPosition() : layoutManager | |
.findLastCompletelyVisibleItemPosition(); | |
// Check if we need to snap | |
if (visiblePosition != completelyVisiblePosition) { | |
recyclerView.smoothScrollToPosition(visiblePosition); | |
return; | |
} | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment