我不能在RecyclerView中禁用滚动。我尝试调用rv.setEnabled(false),但我仍然可以滚动。
我如何禁用滚动?
我不能在RecyclerView中禁用滚动。我尝试调用rv.setEnabled(false),但我仍然可以滚动。
我如何禁用滚动?
当前回答
XML格式:-
你可以添加
android:nestedScrollingEnabled=“false”
在子RecyclerView布局XML文件中
or
在爪哇:-
childRecyclerView.setNestedScrollingEnabled(假);
Java代码中的RecyclerView。
使用ViewCompat (Java):-
childRecyclerView.setNestedScrollingEnabled(假);将只在android_version>21设备上工作。要在所有设备上工作,请使用以下方法
ViewCompat。setNestedScrollingEnabled (childRecyclerView假);
其他回答
由于setLayoutFrozen已弃用,你可以通过使用suppressLayout冻结你的RecyclerView来禁用滚动。
冻结:
recyclerView.suppressLayout(true)
解冻:
recyclerView.suppressLayout(false)
出于某种原因,@Alejandro Gracia的回答在几秒钟后才开始工作。 我发现了一个解决方案,阻止RecyclerView瞬间:
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
return true;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
我知道这个问题已经有了一个公认的答案,但是这个解决方案没有考虑到我遇到的用例。
我特别需要一个标题项,仍然是可点击的,但禁用了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) {
}
});
如果你只是禁用RecyclerView的滚动功能,那么你可以使用setLayoutFrozen(true);RecyclerView的方法。但它不能禁用触摸事件。
your_recyclerView.setLayoutFrozen(true);
创建继承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
...
...
/>