我有水平的Recyclerview,想要禁用它的手动滚动。但是点击项目时应滚动。怎么做?
答案 0 :(得分:1)
在你的电话中实施RecyclerView.OnItemTouchListener它会在recyclerview上偷走所有触摸事件
public class RecyclerViewDisabler implements 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) {
}
}
启用和禁用滚动:
RecyclerView recycleview = ...
RecyclerView.OnItemTouchListener disabler = new RecyclerViewDisabler();
recycleview.addOnItemTouchListener(disabler); // scolling disable
// do what you want to do at time of disable scrolling
recycleview.removeOnItemTouchListener(disabler); // scrolling enabled again
答案 1 :(得分:0)
// You can set `onTouchListener`
public class RecyclerViewTouch implements 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) {
}
}
// Use it
RecyclerView.OnItemTouchListener disable = new RecyclerViewTouch();
rView.addOnItemTouchListener(disable); // disables scolling
rView.removeOnItemTouchListener(disable); // enable the scrolling
答案 2 :(得分:0)
您必须为此创建自定义布局管理器,您可以通过这种方式禁用滚动
示例:强>
public class CustomLayoutManager extends LinearLayoutManager {
private boolean isScrollEnabled = true;
public CustomLayoutManager(Context context) {
super(context);
}
public void setScrollEnabled(boolean flag) {
this.isScrollEnabled = flag;
}
@Override
public boolean canScrollHorizontally() {
//Similarly you can customize "canScrollVertically()" for managing horizontal scroll
return isScrollEnabled && super.canScrollHorizontally();
}
这样你可以禁用手动滚动
答案 3 :(得分:0)
感谢Emi Raz。 他的回答对于在 recyclerview 上禁用滚动行为非常简单。解决方案对我有用。 请参阅他的解决方案here
Java:
LinearLayoutManager lm = new LinearLayoutManager(getContext()) {
@Override
public boolean canScrollVertically() {
return false;
}
};
科特林:
val lm: LinearLayoutManager = object : LinearLayoutManager(requireContext()) {
override fun canScrollVertically(): Boolean { return false }
}