RecyclerView的原生方法
1. smoothScrollToPosition( int position )方法 平滑滾動
2. scrollToPosition(int position) 直接顯示,沒有平滑效果
查看源碼,發現滑動平滑效果,可改變。然後自定義一個LinearLayoutManager ,平滑時間
public class SmoothScrollLayoutManager extends LinearLayoutManager { public SmoothScrollLayoutManager(Context context) { super(context); } @Override public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, final int position) { LinearSmoothScroller smoothScroller = new LinearSmoothScroller(recyclerView.getContext()) { // 返回:滑過1px時經歷的時間(ms)。 @Override protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) { return 100f / displayMetrics.densityDpi; } @Override protected int getHorizontalSnapPreference() { return SNAP_TO_START;//具體見源碼註釋 } @Override protected int getVerticalSnapPreference() { return SNAP_TO_START;//具體見源碼註釋 } }; smoothScroller.setTargetPosition(position); startSmoothScroll(smoothScroller); } }
調用方式:
LinearLayoutManager linelarLayoutManager = new SmoothScrollLayoutManager(this); recycler.setLayoutManager(linelarLayoutManager);
定位時調用:
recycler.smoothScrollToPosition(i);
因爲這裏的滑動效果是自己定義的,可以根據需要修改滑動時間並置頂。 希望對你用幫助,親測可用
如果轉載,請註明出處https://me.csdn.net/fepengwang