實際開發(fā)中很多時候需要recyclerview點擊邊緣的item時有自動滾動到屏幕中間的需求或者二級聯(lián)動中有二級recyclerview的item要居頂?shù)男枰亚W(wǎng)上有很多介紹原理源碼的哗戈,不贅述了门躯,轉(zhuǎn)載需要看源碼執(zhí)行流程點擊查看,最終實現(xiàn)關(guān)鍵是復寫calculateDtToFit這個方法佛致,計算需要執(zhí)行的偏移位置量
居中類型,需要計算item view的中心點滾動方向到指定位置坐標偏移量
斷點下面是橫向居中截圖1-1,手機橫向分辨率1080
image.png
可以看到boxStart是父布局既recyclerview的開始坐標0,
boxEnd是recyclerview的結(jié)束坐標1080辙谜,我們需要的中點坐標既boxStart+(boxEnd-boxStart)/2,這里可能有padding俺榆、margin之類的開始坐標不一定是0,我猜測的装哆,可以自己去調(diào)試罐脊。
viewStart意思點擊的item開始坐標既view的left,viewEnd是item結(jié)束坐標既right,
-而該view的中心點坐標既開始坐標+view寬度的1/2,反正就是那么個意思蜕琴。既viewStart+(viewEnd-viewStart)/2既得該方向中心點位置
上述兩位置相減有正負萍桌,所得結(jié)果既為該item需要偏移滾動的距離。
居頂類型凌简,原理與居中類似上炎,不過不需要計算中心點,直接boxStart-ViewStart
public class CenterLayoutManager extends LinearLayoutManager {
public CenterLayoutManager(Context context) {
super(context);
}
public CenterLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public CenterLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
RecyclerView.SmoothScroller smoothScroller = new CenterSmoothScroller(recyclerView.getContext());
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
private static class CenterSmoothScroller extends LinearSmoothScroller {
public CenterSmoothScroller(Context context) {
super(context);
}
@Override
public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) {
return (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2);
}
@Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return 100f / displayMetrics.densityDpi;
}
}
}
item點擊事件中
RecyclerView.LayoutManager layoutManager = mView.getColorRcv().getLayoutManager();
if (layoutManager != null) {
layoutManager.smoothScrollToPosition(mView.getColorRcv(), new RecyclerView.State(), position);
}