直接使用 smoothScrollToPosition(position) 時,如果要定位的數據在集合下半部分,則滾動結束后,需要顯示的數據是在手機界面地步
可以使用 ((LinearLayoutManager) ((RecyclerView)getView(R.id.rv)).getLayoutManager()).scrollToPositionWithOffset(position, 0) 達到每次滾動結束,數據都是在頂部顯示,但是數據不是平滑滾動的。
如果要實現不論哪種情況,都能讓數據平滑滾動到頂部顯示,需要重寫 LinearLayoutManager
1,覆寫 LinearSmoothScroller
public class TopLinearSmoothScroller extends LinearSmoothScroller { public TopLinearSmoothScroller(Context context) { super(context); } @Override public int getVerticalSnapPreference() { return SNAP_TO_START; } }
2,重寫 recyclerview.LinearLayoutManager 的 smoothScrollToPosition 方法
TopLinearSmoothScroller scroller = new TopLinearSmoothScroller(rv.getContext()); LinearLayoutManager layoutManager = new LinearLayoutManager(context) { @Override public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) { super.smoothScrollToPosition(recyclerView, state, position); scroller.setTargetPosition(position); startSmoothScroll(scroller); } }; rv.setLayoutManager(layoutManager);
3,最后調用 smoothScrollToPosition 即可
rv.smoothScrollToPosition(position);