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

我如何禁用滚动?


当前回答

重写onTouchEvent()和onInterceptTouchEvent()并返回false,如果你根本不需要OnItemTouchListener。 这不会禁用ViewHolders的OnClickListeners。

public class ScrollDisabledRecyclerView extends RecyclerView {
    public ScrollDisabledRecyclerView(Context context) {
        super(context);
    }

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

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

    @Override
    public boolean onTouchEvent(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {
        return false;
    }
}

其他回答

XML格式:-

你可以添加

android:nestedScrollingEnabled=“false”

在子RecyclerView布局XML文件中

or

在爪哇:-

childRecyclerView.setNestedScrollingEnabled(假);

Java代码中的RecyclerView。

使用ViewCompat (Java):-

childRecyclerView.setNestedScrollingEnabled(假);将只在android_version>21设备上工作。要在所有设备上工作,请使用以下方法

ViewCompat。setNestedScrollingEnabled (childRecyclerView假);

答案很简单。

LinearLayoutManager lm = new LinearLayoutManager(getContext()) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            };

上面的代码禁用了RecyclerView的垂直滚动。

另一个替代方案是setLayoutFrozen,但它带来了一堆其他副作用。

https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html setLayoutFrozen(布尔)

遇到了包含多个RecycleView的片段,所以我只需要一个滚动条,而不是每个RecycleView中的一个滚动条。

所以我只是把ScrollView放在父容器中,其中包含2个RecycleViews,并使用android:isScrollContainer="false"在RecycleView

<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layoutManager="LinearLayoutManager"
    android:isScrollContainer="false" />
recyclerView.addOnItemTouchListener(new RecyclerView.SimpleOnItemTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
            // Stop only scrolling.
            return rv.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING;
        }
    });