我不能在RecyclerView中禁用滚动。我尝试调用rv.setEnabled(false),但我仍然可以滚动。
我如何禁用滚动?
我不能在RecyclerView中禁用滚动。我尝试调用rv.setEnabled(false),但我仍然可以滚动。
我如何禁用滚动?
当前回答
如果你只是禁用RecyclerView的滚动功能,那么你可以使用setLayoutFrozen(true);RecyclerView的方法。但它不能禁用触摸事件。
your_recyclerView.setLayoutFrozen(true);
其他回答
这对我来说很管用:
recyclerView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
另一个替代方案是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" />
写了一个kotlin版本:
class NoScrollLinearLayoutManager(context: Context?) : LinearLayoutManager(context) {
private var scrollable = true
fun enableScrolling() {
scrollable = true
}
fun disableScrolling() {
scrollable = false
}
override fun canScrollVertically() =
super.canScrollVertically() && scrollable
override fun canScrollHorizontally() =
super.canScrollVertically()
&& scrollable
}
用法:
recyclerView.layoutManager = NoScrollLinearLayoutManager(context)
(recyclerView.layoutManager as NoScrollLinearLayoutManager).disableScrolling()
API 21及以上版本:
不需要java代码。 你可以设置android:nestedScrollingEnabled="false" 在xml:
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="true"
android:nestedScrollingEnabled="false"
tools:listitem="@layout/adapter_favorite_place">