- 開發(fā)當(dāng)中經(jīng)常會(huì)遇到的產(chǎn)品需求突那,
recycleview
自動(dòng)滾動(dòng)到某一個(gè)位置愿汰。具體場(chǎng)景可能是如下: - 頁(yè)面初始化之后自動(dòng)自動(dòng)跳轉(zhuǎn)到某一個(gè)位置
- 頁(yè)面滾動(dòng)之后要回到某一個(gè)位置
- 為了展示完全需要
recycleview
做微小的位置偏移等
針對(duì)如上問題饶米,我們先來看看recycleview都有什么方法提供給我們婚度。
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();
}
scrollToPosition(int position)
方法掂林,滑動(dòng)到指定position的item的頂部聂薪。
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);
}
smoothScrollToPosition(int position)
方法同上,但是會(huì)有平滑滑動(dòng)的效果方仿。
public void scrollBy(int x, int y) {
if (mLayout == null) {
Log.e(TAG, "Cannot scroll without a LayoutManager set. "
+ "Call setLayoutManager with a non-null argument.");
return;
}
if (mLayoutSuppressed) {
return;
}
final boolean canScrollHorizontal = mLayout.canScrollHorizontally();
final boolean canScrollVertical = mLayout.canScrollVertically();
if (canScrollHorizontal || canScrollVertical) {
scrollByInternal(canScrollHorizontal ? x : 0, canScrollVertical ? y : 0, null);
}
}
scrollBy(int x, int y)
方法通過傳入偏移量進(jìn)行滑動(dòng)固棚。
public void startSmoothScroll(SmoothScroller smoothScroller) {
if (mSmoothScroller != null && smoothScroller != mSmoothScroller
&& mSmoothScroller.isRunning()) {
mSmoothScroller.stop();
}
mSmoothScroller = smoothScroller;
mSmoothScroller.start(mRecyclerView, this);
}
startSmoothScroll(SmoothScroller smoothScroller)
通過傳入一個(gè)SmoothScroller
來控制recycleview
的移動(dòng)。
針對(duì)題前所說的三種情況來說
這個(gè)需求會(huì)涉及到幾種情況如下:
- 目標(biāo)
item
已經(jīng)出現(xiàn)在屏幕當(dāng)中的情況仙蚜,這時(shí)候調(diào)用方法一此洲,方法二是達(dá)不到recycleview進(jìn)行位置的移動(dòng)的。這時(shí)候可以選擇調(diào)用方法三來達(dá)到我們要的效果委粉。
val smoothScroller: RecyclerView.SmoothScroller = object : LinearSmoothScroller(mContext) {
override fun getVerticalSnapPreference(): Int {
return SNAP_TO_START
}
}
smoothScroller.targetPosition = CIRCLE_POSITION + 1
mVirtualLayoutManager.startSmoothScroll(smoothScroller)
當(dāng)然方法四也可以達(dá)到我們所要的效果呜师,這時(shí)候需要算出來的是我們目標(biāo)item距離頂部所需的距離
rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
......
int toTop = rv.getChildAt(n).getTop();
rvProduct.scrollBy(0, top);
......
}
});
- 當(dāng)目標(biāo)
item
如果說并沒有出現(xiàn)在屏幕中時(shí),方法一和方法二就可以達(dá)到我們需要的效果贾节。