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.smoothScrollToPosition(position);