我不能在RecyclerView中禁用滚动。我尝试调用rv.setEnabled(false),但我仍然可以滚动。
我如何禁用滚动?
我不能在RecyclerView中禁用滚动。我尝试调用rv.setEnabled(false),但我仍然可以滚动。
我如何禁用滚动?
当前回答
Add
android:descendantFocusability="blocksDescendants"
在你的子SrollView或NestedScrollView(和父ListView, recyclerview和gridview任意一个)
其他回答
创建继承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 widthMeasureSpec, int heightMeasureSpec) {
int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
}
这将禁用滚动事件,但不会禁用单击事件
在XML中使用它,执行以下操作:
<com.yourpackage.xyx.NonScrollRecyclerView
...
...
/>
我知道这个问题已经有了一个公认的答案,但是这个解决方案没有考虑到我遇到的用例。
我特别需要一个标题项,仍然是可点击的,但禁用了RecyclerView的滚动机制。这可以通过以下代码来完成:
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
return e.getAction() == MotionEvent.ACTION_MOVE;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
答案很简单。
LinearLayoutManager lm = new LinearLayoutManager(getContext()) {
@Override
public boolean canScrollVertically() {
return false;
}
};
上面的代码禁用了RecyclerView的垂直滚动。
为此,您应该重写recycleView的layoutManager。这样它只会禁用滚动,没有其他功能。你仍然能够处理点击或任何其他触摸事件。例如:-
原:
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 }
下面是我如何使用数据绑定:
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false"
android:onTouch="@{(v,e) -> true}"/>
在“true”的地方,我使用了一个基于条件改变的布尔变量,这样回收器视图就会在禁用和启用之间切换。