解决方案

recyclerview.smoothScrollToPosition精确滚动到顶部解决方案

2022-11-25 22:03:51 michael007js 1681

直接使用 smoothScrollToPosition(position) 时,如果要定位的数据在集合下半部分,则滚动结束后,需要显示的数据是在手机界面地步

解决方案是需要重写 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);
首页
关于博主
我的博客
搜索