Skip to content

Instantly share code, notes, and snippets.

@evant
Created July 16, 2015 19:33
Show Gist options
  • Save evant/300bae529b9a540e8585 to your computer and use it in GitHub Desktop.
Save evant/300bae529b9a540e8585 to your computer and use it in GitHub Desktop.
Force item to top instead of just on screen when smooth scrolling with RecyclerView
public class SnapTopLinearLayoutManager extends LinearLayoutManager {
public SnapTopLinearLayoutManager(Context context) {
super(context);
}
public SnapTopLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public SnapTopLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
SnapTopLinearSmoothScroller linearSmoothScroller =
new SnapTopLinearSmoothScroller(recyclerView.getContext()) {
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return SnapTopLinearLayoutManager.this
.computeScrollVectorForPosition(targetPosition);
}
};
linearSmoothScroller.setTargetPosition(position);
startSmoothScroll(linearSmoothScroller);
}
}
public abstract class SnapTopLinearSmoothScroller extends LinearSmoothScroller {
public SnapTopLinearSmoothScroller(Context context) {
super(context);
}
@Override
protected int getVerticalSnapPreference() {
return SNAP_TO_START;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment