我不能在RecyclerView中禁用滚动。我尝试调用rv.setEnabled(false),但我仍然可以滚动。
我如何禁用滚动?
我不能在RecyclerView中禁用滚动。我尝试调用rv.setEnabled(false),但我仍然可以滚动。
我如何禁用滚动?
当前回答
遇到了包含多个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" />
其他回答
您可以在设置适配器之后添加这一行
ViewCompat.setNestedScrollingEnabled(recyclerView, false);
现在您的recyclerview将与平滑滚动工作
我知道这个问题已经有了一个公认的答案,但是这个解决方案没有考虑到我遇到的用例。
我特别需要一个标题项,仍然是可点击的,但禁用了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有一个方法叫做addOnScrollListener(OnScrollListener监听器),使用这个你可以停止滚动,就像这样:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (viewModel.isItemSelected) {
recyclerView.stopScroll();
}
}
});
Use case: Let's say that you want to disable scrolling when you click on one of the items within RecyclerView so you could perform some actions with it, without being distracted by accidentally scrolling to another item, and when you are done with it, just click on the item again to enable scrolling. For that, you would want to attach OnClickListener to every item within RecyclerView, so when you click on an item, it would toggle isItemSelected from false to true. This way when you try to scroll, RecyclerView will automatically call method onScrollStateChanged and since isItemSelected set to true, it will stop immediately, before RecyclerView got the chance, well... to scroll.
注意:为了更好的可用性,尝试使用GestureListener而不是OnClickListener来防止意外点击。
出于某种原因,@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) {
}
});
答案很简单。
LinearLayoutManager lm = new LinearLayoutManager(getContext()) {
@Override
public boolean canScrollVertically() {
return false;
}
};
上面的代码禁用了RecyclerView的垂直滚动。