recyclerview 列表滚动到顶部位置

recyclerview 直接使用smoothScrollToPosition 只能让目标位置滚动到 可视的屏幕中,无法让 目标位置滚到到顶部 或者 底部

在这 我们需要创建一个类LinearLayoutManagerScrollTop来继承LinearLayoutManager重写smoothScrollToPosition 方法

同时创建一个类来继承LinearSmoothScroller重写getVerticalSnapPreference()

public class LinearLayoutManagerScrollTop extends LinearLayoutManager {
    public LinearLayoutManagerScrollTop(Context context) {
        super(context);
    }

    public LinearLayoutManagerScrollTop(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    public LinearLayoutManagerScrollTop(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
        LinearSmoothScrollerTop topScroller = new LinearSmoothScrollerTop(recyclerView.getContext());
        topScroller.setTargetPosition(position);
        startSmoothScroll(topScroller );
    }
}

在getVerticalSnapPreference() 方法中设置 ScrollType

public class LinearSmoothScrollerTop extends LinearSmoothScroller {
    
    private int scrollType= LinearSmoothScroller.SNAP_TO_START
   
    public static final float DEFAULT_MILLISECONDS_PER_INCH = 25f;


    
    @Override
    protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
        return DEFAULT_MILLISECONDS_PER_INCH / displayMetrics.densityDpi;
    }

    
    /**
     * LinearSmoothScroller.SNAP_TO_ANY   默认模式
     * LinearSmoothScroller.SNAP_TO_START 顶部
     * LinearSmoothScroller.SNAP_TO_END   底部
     *  竖向
     */
    @Override
    protected int getVerticalSnapPreference() {
        return scrollType;
    }

    /**
     * LinearSmoothScroller.SNAP_TO_ANY   默认模式
     * LinearSmoothScroller.SNAP_TO_START 顶部
     * LinearSmoothScroller.SNAP_TO_END   底部
     *  横向
     */
    @Override  
    protected int getHorizontalSnapPreference() {
        return super.getHorizontalSnapPreference();
    }
}

使用

LinearLayoutManagerScrollTop  manager = new LinearLayoutManagerScrollTop (this);
mRecyclerView.setLayoutManager(manager);
adapter = new ScrollTopAdapter(this);
mRecyclerView.setAdapter(adapter);
adapter.setList(list);
adapter.notifyDataSetChanged();

// 使用 smoothScrollToPosition
mRecyclerView.smoothScrollToPosition(position);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值