Recycleview滑动方法
smoothScrollBy()
/**
* Animate a scroll by the given amount of pixels along either axis.
*
* @param dx Pixels to scroll horizontally
* @param dy Pixels to scroll vertically
*/
public void smoothScrollBy(@Px int dx, @Px int dy) {
smoothScrollBy(dx, dy, null);
}
需要提供滑动的距离,具有平滑效果
smoothScrollToPosition()
/**
* Starts a smooth scroll to an adapter position.
* <p>
* To support smooth scrolling, you must override
* {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} and create a
* {@link SmoothScroller}.
* <p>
* {@link LayoutManager} is responsible for creating the actual scroll action. If you want to
* provide a custom smooth scroll logic, override
* {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} in your
* LayoutManager.
*
* @param position The adapter position to scroll to
* @see LayoutManager#smoothScrollToPosition(RecyclerView, State, int)
*/
public void smoothScrollToPosition(int position) {
if (mLayoutSuppressed) {
return;
}
if (mLayout == null) {
Log.e(TAG, "Cannot smooth scroll without a LayoutManager set. "
+ "Call setLayoutManager with a non-null argument.");
return;
}
mLayout.smoothScrollToPosition(this, mState, position);
}
这个方法只保证指定的item被滑动到屏幕中,意味着自下往上滑的话,可以将指定item置顶,但是如果已经在屏幕中的话,那他就不会起作用,并且如果是自上往下滑的话,则置顶的item就会被滑到底部
具有平滑效果
scrollToPosition()
/**
* Convenience method to scroll to a certain position.
*
* RecyclerView does not implement scrolling logic, rather forwards the call to
* {@link RecyclerView.LayoutManager#scrollToPosition(int)}
* @param position Scroll to this adapter position
* @see RecyclerView.LayoutManager#scrollToPosition(int)
*/
public void scrollToPosition(int position) {
if (mLayoutSuppressed) {
return;
}
stopScroll();
if (mLayout == null) {
Log.e(TAG, "Cannot scroll to position a LayoutManager set. "
+ "Call setLayoutManager with a non-null argument.");
return;
}
mLayout.scrollToPosition(position);
awakenScrollBars();
}
没有任何效果的移动到指定position
LayoutManager滑动方法
scrollToPositionWithOffset
这种方式是定位到指定项如果该项可以置顶就将其置顶显示
参看demo:
实现滚动方案:
https://github.com/z-chu/RecyclerView-Scroll-Sample
平滑滚动方案:
https://github.com/SilentSword2020/RecyclerViewScrollTop
网友评论