Android scrolltoposition dont work

📃RecyclerView SmoothScrollToPosition Not Working within NestedScrollView Solution— Android.✔

Scroll your recycler view within a Nested scroll view easily

Oct 5, 2019 · 3 min read

T his Story belongs to what I have learned today. As you can see from the article title that recyclerView smoothScrollToPosition() not working within NestedScrollView, now how the layout file looks like and what I mean to say that all the confusion will be clear so you can see the XML file from the below Snippet.

I had a case that I have a screen with a top static section and then I have a recycler view in which I need to show the comments list. And I need to scroll the whole screen that’s why I used NestedScrollView.

Wh e n the user sends a comment it will be displayed on the top of the List means on 0 positions, so in my case, I need to scroll the List to 0 positions whenever user comments.

The screen which I used is like the below image.

After so many efforts I came to the solution, that recyclerView scroll not working whenever we add within the nested scroll view. That is why smoothScrollToPosition() not working.

Now, without wasting the time let’s jump to the solution 🛫

Solution:

The solution is to use nestedscroll.smoothScrollTo(0,0) here you need to use the nested scroll Id.

Now, this will let you move towards the top of the screen, but in my case, I need to scroll from where I started the recycler view, so for that, you need to use the view height and need to define in your Y position like below:

Conclusion

This article described you to how RecyclerView SmoothScrollToPosition working within NestedScrollView.

I hope this article is helpful. If you think something is missing, have questions, or would like to give feedback, go ahead and leave a comment below. I’d appreciate the feedback.

I’ve written some other Android-related content, and if you liked what you read here, you’ll probably also enjoy this:

Источник

[SOLVED] RecyclerView: scrollToPosition not working

  • Posted by Finco Agbontaen
  • 1 Comment
  • Categories: Android Apps, Android Errors & Solutions, Tutorials
Читайте также:  Как установить голос андроида

Sometimes when working on an android app, you might need to programmatically scroll a RecyclerView to a position. For example a chat screen. That’s when the recyclerView.scrollToPosition() method comes in.

However, this method sometimes does not work and will simply do nothing.

Cause

The are several reasons that can cause the scrollToPosition() method to not work, however I will describe just one of the reasons in this post

Setting layoutManager.setReverseLayout(true)

According to the docs here:

Used to reverse item traversal and layout order. This behaves similar to the layout change for RTL views. When set to true, first item is laid out at the end of the UI, second item is laid out before it etc. For horizontal layouts, it depends on the layout direction. When set to true, If RecyclerView is LTR, than it will layout from RTL, if RecyclerView> is RTL, it will layout from LTR. If you are looking for the exact same behavior of setStackFromBottom(boolean) , use setStackFromEnd(boolean)

So basically, when you reverse the RecyclerView’s layout, the indexes of the RecyclerView also reverses.

Solution

The solution depends on the exact cause of the problem.

  • If the cause is due to setReverseLayout(true) being set, then you can easily solve the problem by simply making sure that the index you pass to recyclerView.scrollToPosition() is not greater than the list size – 1.Also, if you are trying to scroll to the end of the list, you should pass 0 to the scrollToPosition() method instead of the length of the list – 1.
  • If the cause of the issue is unknown, then this solution is for you.Up till now, I have not had the time to debug the RecyclerView class in order to figure out why this method fails at times, however, the RecyclerView.smoothScrollToPosition(position); method seems to always work in all scenarios.

And that’s all for now.

If you have any questions or contributions, feel free to post them in the comment box below

Источник

Scroll to position not working in your adapter. #7

Comments

arkinaforlife commented May 30, 2016

When i want to scroll to a specific item in recyclerview with for example: mRecyclerview.scrollToPosition(20), the adapter list will not move, but start normally by the first item.
It also happens when i call scroll to position from your StickyLayoutManager.

Is there an way i can fix this issue?

Thanks in advance,

The text was updated successfully, but these errors were encountered:

ShamylZakariya commented Jun 5, 2016 •

I was away on vacation until yesterday — sorry for the delay.

After doing some research, it’s clear that scrollToPosition is implemented in the LayoutManager, not RecyclerView. I’ll get cracking on it, as well as smoothScrollToPosition.

Читайте также:  Kaspersky safe kids для андроид

arkinaforlife commented Jun 5, 2016 •

Thx for your response,

When you’re working on scrollToPosition it may also be important to save the scroll position in onsaveInstance. You can do this by calling: currPosition = recyclerView.findFirstVisibleItemPosition();
The findFirstVisibleItemPosition() method is also an method in the linearlayout manager. I think it’s important to have this part also in your stickylayout manager.

Keep up the good work!

ShamylZakariya commented Jun 6, 2016

I’ve implemented scrollToPosition and smoothScrollToPosition in the adapter, and they appear to work though I will be testing them further. That being said, I have a serious performance issue with HUGE datasets (hundreds of sections, thousands of items) which I want to tackle before I push an update to bintray. I expect to have that taken care of in a couple days, and I’ll let you know and close this issue.

ShamylZakariya commented Jun 6, 2016

I’ve also fixed a huge performance problem, so I’ll be posting an update to bintray tonight, or so.

arkinaforlife commented Jun 8, 2016 •

Great work man, i’ve just two more questions for you:

  • if i have 20 items with sticky header in my adapter, when i press on item 3 in grid. I want to show item 3 in adapter, but it shows item 1. Do you have an solution for this, so that it scrolls to the exact item.
    (What i do now to achieve this is multiply the pressed item with 3, i don’t know if this is the recommended solution)
  • If i leave my activity or fragment i want to save the item that is visible to the user when leaving, so i can scroll back in onsaveinstance to the last visible item how does this works in your stickylayoutmanager?

Thanks in advance!

ShamylZakariya commented Jun 8, 2016

I’m implementing saved state for the StickyHeaderLayoutManager. It likely won’t be completely automatic, though. You’ll still need to explicitly pack and restore state in your activity’s onSaveInstanceState, etc. See here: http://stackoverflow.com/questions/28236390/recyclerview-store-restore-state-between-activities — I’ll report when I’ve got this working.

Regarding your first point, about jumping to position, this is an interesting quandary. When you request smoothScrollToPosition or scrollToPosition, you’re passing an adapter position, which includes headers (and «ghost headers», used internally by the library). This means that if you’re looking at the first item of the first section, your adapter position would actually be 3.

Источник

(Smooth)ScrollToPosition не работает должным образом с RecyclerView

Я использую базовый RecyclerView с GridLayoutManager. Я заметил, что ни smoothScrollToPosition ни scrollToPosition работает правильно.

a) при использовании smoothScrollToPosition Я часто получаю ошибку RecyclerView

«RecyclerView» прошел через целевую позицию при плавной прокрутке.»

и RecyclerView прокручивается неправильно (часто он пропускает целевую строку). Это наблюдается в основном, когда я пытаюсь прокрутить до 1-го пункта некоторых row

Читайте также:  One plus это андроид

b) при использовании scrollToPosition это, кажется, вполне нормально работать, но большую часть времени я вижу только 1-й элемент строки, а остальные не отображаются.

можете ли вы дать мне несколько советов, как заставить работать правильно хотя бы один из методов?

6 ответов

наконец-то я смог заставить его работать! LinearLayoutManager.scrollToPositionWithOffset(int, int) сделал свое дело.

у меня также есть такая же проблема, но мне удалось исправить эту проблему, настроив SmoothScroller

пусть пользовательский LayoutManager, как показано ниже

(документация прокомментирована внутри кода, приведенного выше)пожалуйста, установите вышеуказанный LayoutManager в recyerview

С помощью пользовательского макета менеджер

scrollToPosition также хорошо работает в моем случае вы можете использовать

также, если вы хотите отрегулировать скорость smoothScrollToPosition пожалуйста, переопределите

в CustomLayoutManager. Поэтому, если мы поставим значение как 1f smoothScrollToPosition будет быстрее, как scrollToPosition.увеличение значения делает задержку и уменьшение сделает скорость прокрутки. Надеюсь, это будет полезно.

Источник

How to scroll RecyclerView to a certain position?

This questions seems so simple, in fact Android SDK has provided several API to scroll item at certain position.

It should work as expected right? Afterall, scrolling an item to certain position is a fairly common usage. Yet, why does this question is still popular?

Me too, is a victim of this bug. I have spent years before I realised I was asking the wrong question, before I’ll answer this question, let me show you what I previously had done before.

This is a bit hacky, but always works (in my scenario). Try to reduce the delay, usually 500 milliseconds is enough.

The right question to ask about scrollToPosition is not How, but When.

When to scroll RecyclerView to a certain position?

I find that the problem why scrollToPosition , and others API, does not work is because the dataset is not yet ready. We should call scrollToPosition when the recyclerView has received dataset. To do that, we can use AdapterDataObserver .

AdapterDataObserver has five public methods.

As the method name implies, onItemRangeInserted is called when an item is added to the RecyclerView, and onItemRemoved is called when an item is removed from the RecyclerView.

There is an exception for onChanged . onChanged is only called when you call notify on an Adapter, it is not going to called everytime there is a change on the RecyclerView.

I usually call scrollToPosition when the dataset is succesfully inserted to a RecyclerView, for example:

This way, we don’t have to wait certain millisecond to scroll a ReyclerView. When there is a new dataset, we can trigger scrollToPosition or smoothScrollToPosition and be sure RecyclerView is scrolled.

Источник

Оцените статью