android中recyclerview禁止滑动怎么实现

2024-03-29

要禁止RecyclerView的滑动,可以通过设置其LayoutManager为一个自定义的LayoutManager,并在该自定义LayoutManager中重写canScrollHorizontally()和canScrollVertically()方法,使其返回false,从而禁止RecyclerView的滑动。以下是一个示例代码:

public class CustomLayoutManager extends LinearLayoutManager {
    private boolean isScrollEnabled = true;

    public CustomLayoutManager(Context context) {
        super(context);
    }

    public void setScrollEnabled(boolean flag) {
        this.isScrollEnabled = flag;
    }

    @Override
    public boolean canScrollHorizontally() {
        return isScrollEnabled && super.canScrollHorizontally();
    }

    @Override
    public boolean canScrollVertically() {
        return isScrollEnabled && super.canScrollVertically();
    }
}

然后在使用RecyclerView的地方,将LayoutManager设置为该自定义LayoutManager,并调用setScrollEnabled(false)方法来禁止滑动:

CustomLayoutManager layoutManager = new CustomLayoutManager(getContext());
layoutManager.setScrollEnabled(false);
recyclerView.setLayoutManager(layoutManager);