设置RecyclerView是否可以滑动

本文介绍两种在项目中控制RecyclerView(RV)滑动状态的方法。第一种针对NestedScrollView嵌套场景,通过设置setNestedScrollingEnabled实现。第二种涉及自定义LayoutManager,如GridLayoutManager,允许在垂直和水平方向上控制滑动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在做项目的时候可能遇到过根据不同场景设置RV是否可以滑动,下面我就介绍我知道的两种方式。

第一种

如果RV外层嵌套的是NestedScrollView那就非常简单了,如下

//传true 可以滑动 false不可以滑动
RecyclerView.setNestedScrollingEnabled(boolean canScroll);

注意设置setNestedScrollingEnabled(false)后RV就不复用了。

第二种

自己定义一个LayoutManager,我就拿GridLayoutManager来说了 。垂直水平都可以设置,看代码就懂了。

public class XGridLayoutManager extends GridLayoutManager {

    private boolean canScroll = true;

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

    public XGridLayoutManager(Context context, int spanCount) {
        super(context, spanCount);
    }

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

    /**
     * 垂直方向
     * @return
     */
    @Override
    public boolean canScrollVertically() {
        return canScroll && super.canScrollVertically();
    }

    /**
     * 水平方向
     * @return
     */
    @Override
    public boolean canScrollHorizontally() {
        return super.canScrollHorizontally();
    }

    /**
     * 设置是否可以滑动
     * @param canScroll
     */
    public void setCanScroll(boolean canScroll) {
        this.canScroll = canScroll;
    }
}

在activity中直接setCanScroll就可以设置是否可以滑动了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值