學(xué)廢了,分享出來(lái)
1、scrollToPosition滾動(dòng)指定item到RecyclerView頂部
這個(gè)就很簡(jiǎn)單,調(diào)用RecyclerView的layoutManager.scrollToPositionWithOffset(position, 0);即可
2、smoothScrollToPosition滾動(dòng)指定item到RecyclerView頂部
這個(gè)是平滑帶動(dòng)畫的滾動(dòng)
原理:recyclerView的smoothScrollToPosition方法中調(diào)用了LayoutManager的滑動(dòng)方法。
LinearLayoutManager的smoothScrollToPosition()方法源碼↓↓↓↓↓
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
int position) {
LinearSmoothScroller linearSmoothScroller =
new LinearSmoothScroller(recyclerView.getContext());
linearSmoothScroller.setTargetPosition(position);
startSmoothScroll(linearSmoothScroller);
}
發(fā)現(xiàn)LinearLayoutManager的smoothScrollToPosition()方法中new 了一個(gè)LinearSmoothScroller 的東西來(lái)控制其滑動(dòng),我們重寫LinearSmoothScroller :
我們重寫calculateDtToFit()方法,即可實(shí)現(xiàn)smoothScrollToPosition()使item自動(dòng)置頂功能.
public class StickyTopicScroller extends LinearSmoothScroller {
public StickyTopicScroller(Context context) {
super(context);
}
@Override
public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) {
//原本的返回值
//return super.calculateDtToFit(viewStart, viewEnd, boxStart, boxEnd, snapPreference);
//修改,返回item置頂?shù)钠屏? return boxStart - viewStart;
}
@Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return super.calculateSpeedPerPixel(displayMetrics);
}
}
如上方法實(shí)現(xiàn)了item自動(dòng)置頂功能,我們自定義StickyTopicItemLayoutManager繼承LinearLayoutManager 重寫smoothScrollToPosition方法,方法中設(shè)置上面的StickyTopicScroller
public class StickyTopicItemLayoutManager extends LinearLayoutManager {
private Context mContext;
public StickyTopicItemLayoutManager(Context context) {
super(context);
mContext = context;
}
public StickyTopicItemLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public StickyTopicItemLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
StickyTopicScroller stickyTopicScroller = new StickyTopicScroller(mContext);
stickyTopicScroller.setTargetPosition(position);
startSmoothScroll(stickyTopicScroller);
}
}
使用
給recyclerView設(shè)置我們重寫的StickyTopicItemLayoutManager
recyclerView.setLayoutManager(new StickyTopicItemLayoutManager(this));
調(diào)用平滑滾動(dòng)即可實(shí)現(xiàn)我們想要的置頂
recyclerView.smoothScrollToPosition(position);
說(shuō)明
smoothScrollToPosition置頂摘自這篇文章---RecyclerView 滾動(dòng)到指定position,并置頂