Android RecyclerView smoothScrollToPosition 滚动到指定位置的一些问题和解决方案

直接使用 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 是 RecyclerView 对象 rv.smoothScrollToPosition(position);
我的笔记
你可能想看的