RecyclerView向我們提供了若干個(gè)方法來(lái)進(jìn)行滾動(dòng):
(1).scrollTo(int x, int y)
Set the scrolled position of your view.
(2).scrollBy(int x, int y)
Move the scrolled position of your view.
(3).scrollToPosition(int position)
Convenience method to scroll to a certain position. RecyclerView does not implement scrolling logic, rather forwards the call to RecyclerView.LayoutManager.scrollToPosition(int)
前面2個(gè)方法需要我們?nèi)タ刂埔苿?dòng)的距離卧须,自己計(jì)算高度或者寬度弄痹。在動(dòng)態(tài)的布局中且各項(xiàng)樣式高度可能都不一樣的情況下设拟,比較有難度程储。
使用第3個(gè)方法scrollToPosition時(shí)蹭沛,移動(dòng)到當(dāng)前屏幕可見(jiàn)列表的前面的項(xiàng)時(shí),它會(huì)將要顯示的項(xiàng)置頂章鲤。但是移動(dòng)到后面的項(xiàng)時(shí)摊灭,一般會(huì)顯示在最后的位置。
因此败徊,綜合以上兩個(gè)方法帚呼,我們可以先用scrollToPosition方法,將要置頂?shù)捻?xiàng)先移動(dòng)顯示出來(lái)集嵌,然后計(jì)算這一項(xiàng)離頂部的距離萝挤,用scrollBy完成最后距離的滾動(dòng)。
1.讓置頂?shù)哪且豁?xiàng)在當(dāng)前屏幕可見(jiàn)
private void scrollToNextShotDate(List<BabyVaccineGroup> vaccineGroupList) {
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getRecyclerView().getLayoutManager();
//獲取當(dāng)前RecycleView屏幕可見(jiàn)的第一項(xiàng)和最后一項(xiàng)的Position
int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
if (nextPosition < firstVisibleItemPosition) {
//要置頂?shù)捻?xiàng)在當(dāng)前顯示的第一項(xiàng)之前
getRecyclerView().smoothScrollToPosition(nextShotPosition);
} else if (nextPosition < lastVisibleItemPosition) {
//要置頂?shù)捻?xiàng)已經(jīng)在屏幕上顯示根欧,計(jì)算它離屏幕原點(diǎn)的距離
int top = getRecyclerView().getChildAt(nextShotPosition - firstVisibleItemPosition).getTop();
getRecyclerView().smoothScrollBy(0, top);
} else {
//要置頂?shù)捻?xiàng)在當(dāng)前顯示的最后一項(xiàng)之后
mShouldScroll = true;
getRecyclerView().smoothScrollToPosition(nextShotPosition);
}
}
2.添加滾動(dòng)監(jiān)聽(tīng)怜珍,當(dāng)完成第一次滾動(dòng)后,進(jìn)行第二次的滾動(dòng)
private class RcvScrollListener extends RecyclerView.OnScrollListener {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (mShouldScroll && newState == RecyclerView.SCROLL_STATE_IDLE) {
mShouldScroll = false;
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getRecyclerView().getLayoutManager();
int n = nextPosition - linearLayoutManager.findFirstVisibleItemPosition();
if (n >= 0 && n < getRecyclerView().getChildCount()) {
//獲取要置頂?shù)捻?xiàng)頂部距離RecyclerView頂部的距離
int top = getRecyclerView().getChildAt(n).getTop();
//進(jìn)行第二次滾動(dòng)(最后的距離)
getRecyclerView().smoothScrollBy(0, top);
}
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
}
}