如何禁用 RecyclerView 滚动?

新手上路,请多包涵

我无法在 RecyclerView 中禁用滚动。我尝试调用 rv.setEnabled(false) 但我仍然可以滚动。

如何禁用滚动?

原文由 Zsolt Safrany 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.8k
2 个回答

为此,您应该覆盖 layoutManagerrecycleView 。这样它只会禁用滚动,没有其他功能。您仍然可以处理点击或任何其他触摸事件。例如:-

原来的:

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

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

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

    @Override
    public boolean canScrollVertically() {
        //Similarly you can customize "canScrollHorizontally()" for managing horizontal scroll
        return isScrollEnabled && super.canScrollVertically();
    }
}

在这里使用“isScrollEnabled”标志,您可以临时启用/禁用回收视图的滚动功能。

还:

简单地覆盖您现有的实现以禁用滚动并允许单击。

 linearLayoutManager = new LinearLayoutManager(context) {
    @Override
    public boolean canScrollVertically() {
        return false;
    }
};

在科特林:

 object : LinearLayoutManager(this) { override fun canScrollVertically() = false }

原文由 Saurabh Garg 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以创建一个扩展 Recycler View 类的 Non Scrollable Recycler View,如下所示:

 import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

public class NonScrollRecyclerView extends RecyclerView {

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

    public NonScrollRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public NonScrollRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasure, int heightMeasure) {
        int heightMeasureCustom = MeasureSpec.makeMeasureSpec(
                Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasure, heightMeasureCustom);
        ViewGroup.LayoutParams params = getLayoutParams();
        params.height = getMeasuredHeight();
    }
}

原文由 Aman Garg 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题