How to disable RecyclerView scrolling?
Posted by: admin November 28, 2017 Leave a comment
I cannot disable scrolling in the RecyclerView . I tried calling rv.setEnabled(false) but I can still scroll.
How can I disable scrolling?
You should override the layoutmanager of your recycleview for this. This way it will only disable scrolling, none of ther other functionalities. You will still be able to handle click or any other touch events. For example:-
Original:
Here using “isScrollEnabled” flag you can enable/disable scrolling functionality of your recycle-view temporarily.
Simple override your existing implementation to disable scrolling and allow clicking.
The real answer is
This a bit hackish workaround but it works; you can enable/disable scrolling in the RecyclerView .
This is an empty RecyclerView.OnItemTouchListener stealing every touch event thus disabling the target RecyclerView .
This works for me:
Extend the LayoutManager and override canScrollHorizontally() and canScrollVertically() to disable scrolling.
Be aware that inserting items at the beginning will not automatically scroll back to the beginning, to get around this do something like:
Another alternative is setLayoutFrozen , but it comes with a bunch of other side effects.
You can also set android:nestedScrollingEnabled=»false»
in xml:
I know this already has an accepted answer, but the solution doesn’t take into account a use-case that I came across.
I specifically needed a header item that was still clickable, yet disabled the scrolling mechanism of the RecyclerView. This can be accomplished with the following code:
For some reason @Alejandro Gracia answer starts working only after a few second.
I found a solution that blocks the RecyclerView instantaneously:
Override onTouchEvent() and onInterceptTouchEvent() and return false if you don’t need OnItemTouchListener at all.
This does not disable OnClickListeners of ViewHolders.
Create class which extend RecyclerView class
This will disable the scroll event, but not the click events
Use this in your XML do the following:
I have been struggling in this issue for some hour,
So I would like to share my experience,
For the layoutManager solution it is fine but if u want to reEnable scrolling the recycler will back to top.
The best solution so far (for me at least) is using @Zsolt Safrany methode but adding getter and setter so you don’t have to remove or add the OnItemTouchListener.
Here is how I did it with data binding:
In place of the “true” I used a boolean variable that changed based on a condition so that the recycler view would switch between being disabled and enabled.
Источник
Как отключить прокрутку RecyclerView?
Я не могу отключить прокрутку в RecyclerView . Я попытался вызвать rv.setEnabled(false) но я все еще могу прокручивать.
Как отключить прокрутку?
Для этого вы должны переопределить layoutmanager вашего recycleview. Таким образом, он будет отключать прокрутку, ни одну из других функций. Вы по-прежнему сможете обрабатывать клики или любые другие события касания. Например:-
Оригинал:
Здесь, используя флаг isScrollEnabled, вы можете временно включать / отключать функции прокрутки вашего временного цикла.
Также:
Просто переопределите существующую реализацию, чтобы отключить прокрутку и разрешить щелчок.
Дополнительная информация в документации
Это немного хакерское решение, но оно работает; Вы можете включить / отключить прокрутку в RecyclerView .
Это пустой RecyclerView.OnItemTouchListener крадущий каждое событие касания, таким образом отключая целевой RecyclerView .
Это работает для меня:
Расширьте LayoutManager и переопределите canScrollHorizontally() и canScrollVertically() чтобы отключить прокрутку.
Имейте в виду, что вставка элементов в начале не будет автоматически прокручиваться назад до начала, чтобы обойти это:
Другой альтернативой является setLayoutFrozen , но он поставляется с рядом других побочных эффектов.
Я знаю, что у этого уже есть принятый ответ, но решение не учитывает прецедент, с которым я столкнулся.
Мне определенно нужен элемент заголовка, который по-прежнему доступен для кликов, но отключил механизм прокрутки RecyclerView. Это может быть выполнено с помощью следующего кода:
Вы также можете установить android:nestedScrollingEnabled=»false» в xml:
Почему-то ответ @Alejandro Gracia начинает работать только через несколько секунд. Я нашел решение, которое мгновенно блокирует RecyclerView:
Создать класс, который расширяет класс RecyclerView
Это отключит событие прокрутки, но не события кликов
Используйте это в своем XML, чтобы сделать следующее:
Переопределите onTouchEvent () и onInterceptTouchEvent () и верните false, если вам вообще не нужен OnItemTouchListener. Это не отключает OnClickListeners ViewHolders.
Я боролся в этой проблеме в течение некоторого часа. Поэтому я хотел бы поделиться своим опытом. Для решения layoutManager это нормально, но если вы хотите повторно использовать прокрутку, то переработчик вернется к началу.
Лучшее решение пока (для меня, по крайней мере) использует метод @Zsolt Safrany, но добавляет getter и setter, поэтому вам не нужно удалять или добавлять OnItemTouchListener.
Вот как я это сделал с привязкой данных:
Вместо «true» я использовал логическую переменную, которая была изменена в зависимости от состояния, так что просмотр recycler переключился бы между отключением и включением.
Источник
Как отключить скроллинг RecyclerView?
Я не могу отключить прокрутку в RecyclerView . Я пытался дозвониться РВ.setEnabled(false), то` но я все еще могу прокрутить.
Как я могу отключить прокрутку?
Вы должны переопределить LayoutManager из вашего recycleview для этого. Таким образом, это будет только отключить прокрутку, ни одна из других функций. Вы все еще быть в состоянии обрабатывать кнопку или любого другого события касания. Например:-
Оригинале:
Вот через «и isScrollEnabled» и флаг вы можете включить/отключить функцию прокрутки вашей корзины-смотреть временно.
Также:
Просто переопределить существующие реализации для отключения прокрутки и позволяют нажатием.
Реальный реальный ответ: Для API 21 и выше:
Нет Java-код. Вы можете установить андроида:nestedScrollingEnabled=то»ложные»`в в XML:
Это немного программистские временное решение, но это работает; вы можете включить/отключить прокрутку в RecyclerView`.
Это пустой RecyclerView.OnItemTouchListener кража каждое прикосновение событие, таким образом, отключение RecyclerView цели«.
Это работает для меня:
Вы можете отключить прокрутку при замораживании вашего RecyclerView.
Чтобы заморозить: recyclerView.setLayoutFrozen(правда)
Чтобы разморозить: recyclerView.setLayoutFrozen(ложные)
Создать класс, который распространяется RecyclerView класс
Это позволит отключить событие Scroll, но не события click
Используйте это в ваших XML выполните следующие действия:
Если вы просто отключите только функцию прокрутки от RecyclerView, то вы можете использовать setLayoutFrozen(истина); метод RecyclerView . Но его нельзя отключить сенсорные события.
Другой альтернативой является setLayoutFrozen , но это приходит с кучей других побочных эффектов.
Написал версию Котлин:
Расширить LayoutManager выполняет и переопределить canScrollHorizontally() и canScrollVertically () , чтобы отключить прокрутку.
Помните, что вставка элементов в начале не будет автоматически прокручивать назад к началу, чтобы обойти это сделать что-то вроде:
Я знаю, что это уже есть принятый ответ, но решение не’т принять во внимание случай с которым я столкнулся.
Мне конкретно нужен элемент заголовка, который был по-прежнему кликабельны, но отключен механизм прокрутки RecyclerView. Это можно сделать с помощью следующего кода:
Есть очень простой ответ.
Приведенный выше код отключает RecyclerView вертикальной прокрутки.
Переопределить onTouchEvent() и onInterceptTouchEvent() и возвращать false, если вы не’т нужна OnItemTouchListener на всех. Это не отключает OnClickListeners из ViewHolders.
Вы можете добавить эту строку после установки адаптера
Теперь ваш recyclerview совместимость с плавной прокруткой
По какой-то причине @Алехандро ответ Грасия начинает работать через несколько секунд. Я нашел решение, которое блокирует RecyclerView мгновенно:
Я борюсь в этом вопросе за какой-то час, Поэтому я хотел бы поделиться своим опытом, Для LayoutManager выполняет решение это хорошо, но если вы хотите, чтобы включить прокрутку переработчик будет вернуться к началу.
Лучшее решение до сих пор (по крайней мере для меня) с помощью @Жолт Safrany компания Methode но добавить геттер и сеттер, так что вы Дон’т придется удалить или добавить OnItemTouchListener.
в XML :-
Вы можете добавить
у ребенка RecyclerView XML-файл макета
в Java :-
к вашему RecyclerView в Java-код.
Используя ViewCompat (Ява) :-
Источник
android — overscrollmode — How to disable RecyclerView scrolling?
recyclerview disable auto scroll (16)
I cannot disable scrolling in the RecyclerView . I tried calling rv.setEnabled(false) but I can still scroll.
How can I disable scrolling?
in your child of SrollView or NestedScrollView (and parent of ListView, recyclerview and gridview any one)
Another alternative is setLayoutFrozen , but it comes with a bunch of other side effects.
Create class which extend RecyclerView class
This will disable the scroll event, but not the click events
Use this in your XML do the following:
Extend the LayoutManager and override canScrollHorizontally() and canScrollVertically() to disable scrolling.
Be aware that inserting items at the beginning will not automatically scroll back to the beginning, to get around this do something like:
Here is how I did it with data binding:
In place of the «true» I used a boolean variable that changed based on a condition so that the recycler view would switch between being disabled and enabled.
I have been struggling in this issue for some hour, So I would like to share my experience, For the layoutManager solution it is fine but if u want to reEnable scrolling the recycler will back to top.
The best solution so far (for me at least) is using @Zsolt Safrany methode but adding getter and setter so you don’t have to remove or add the OnItemTouchListener.
If you just disable only scroll functionality of RecyclerView then you can use setLayoutFrozen(true); method of RecyclerView . But it can not be disable touch event.
Just add this to your recycleview in xml
The REAL REAL answer is: For API 21 and higher:
No java code needed. You can set android:nestedScrollingEnabled=»false» in xml:
The real answer is
There is a realy simple answer.
The above code disables RecyclerView vertically scrolling.
This a bit hackish workaround but it works; you can enable/disable scrolling in the RecyclerView .
This is an empty RecyclerView.OnItemTouchListener stealing every touch event thus disabling the target RecyclerView .
Wrote a kotlin version:
You can add this line after setting your adapter
Now your recyclerview will work with smooth scrolling
You should override the layoutmanager of your recycleview for this. This way it will only disable scrolling, none of ther other functionalities. You will still be able to handle click or any other touch events. For example:-
Original:
Here using «isScrollEnabled» flag you can enable/disable scrolling functionality of your recycle-view temporarily.
Simple override your existing implementation to disable scrolling and allow clicking.
in XML :-
in the child RecyclerView layout XML file
in Java :-
to your RecyclerView in Java code.
Using ViewCompat (Java) :-
Источник
Fast Scrolling with RecyclerView
Aug 26, 2017 · 3 min read
Continuing with Support Library 26 features (if you missed the one with downloadable fonts), a much awaited feature was enabled : fast scrolling for RecyclerView.
Of all the great advantages RecyclerView has over ListView, one feature that I miss a lot is fast scrolling where you could drag a thumb drawable and scroll around the list. In ListView you could do the following :
But with RecyclerView, there is no easy way to have a thumb drawable like so :
So we would rely on libraries like this and this.
With Suppo r t Library 26, we can easily enable fast scrolling for RecyclerView. Let’s get to it!
Let’s make sure we’re getting the Support Library 26. The app build.gradle file will look something like :
Since Support Library 26 has now been moved to Google’s maven repository, let’s include that in our project level build.gradle
This is what our layout file for the activity looks like :
I have setup a simple RecyclerView filled with mock data that shows US states and their state code. It looks something like :
Now let’s enable the fast scrolling. The updated xml file looks like :
Let’s go over each property one by one :
- fastScrollEnabled : boolean value to enable the fast scrolling. Setting this as true will require that we provide the following four properties.
- fastScrollHorizontalThumbDrawable : A StateListDrawable that will be used to draw the thumb which will be draggable across the horizontal axis.
- fastScrollHorizontalTrackDrawable : A StateListDrawable that will be used to draw the line that will represent the scrollbar on horizontal axis.
- fastScrollVerticalThumbDrawable : A StateListDrawable that will be used to draw the thumb which will be draggable on vertical axis.
- fastScrollVerticalTrackDrawable : A StateListDrawable that will be used to draw the line that will represent the scrollbar on vertical axis.
Let’s look at the StateListDrawables. I’ve used native shapes so that you can easily reuse them.
Источник