Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView inside NestedScrollView does not give correct visible item position

I have a RecyclerView inside a NestedScrollView and I'm trying to get the position of the last visible list item during scroll events using. The following code allows me to reliably detect scroll events:

val recyclerView = nestedScrollView.getChildAt(0) as RecyclerView

nestedScrollView.setOnScrollChangeListener { v: NestedScrollView?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int ->
    val layoutManager = recyclerView?.layoutManager as? LinearLayoutManager
    val lastVisiblePosition = layoutManager?.findLastVisibleItemPosition()
}

The problem however is that here lastVisiblePosition always ends up being the last item in the list whether this is actually on scree or not. Where could I be going wrong?

like image 293
Spaci Tron Avatar asked Jan 24 '18 17:01

Spaci Tron


People also ask

What is nested scrolling in RecyclerView?

NestedScrollView is just like ScrollView, but it supports acting as both a nested scrolling parent and child. In your case you have to define your own scrolling behaviour.

Why we use nested scroll view?

NestedScrollView is used when there is a need for a scrolling view inside another scrolling view.

What is nested scroll view?

NestedScrollView is just like ScrollView , but it supports acting as both a nested scrolling parent and child on both new and old versions of Android. Nested scrolling is enabled by default.


1 Answers

If you put a RecyclerView inside a scrollable container—a NestedScrollView in your case—it will basically become a fancy LinearLayout, inflating and showing all the items at once. You get the first and last item as the first and last one visible because—to the RecyclerView—they are. All the items got inflated and added, so all of them are "visible on screen" inside the scrollable view.

The easy solution would be to just not nest the RecyclerView inside the NestedScrollView. A RecyclerView can scroll already, so you could just put whatever header or footer you need inside the RecyclerView as well. Nesting scrollable views always has drawbacks and you should try to avoid it whenever possible.

like image 153
David Medenjak Avatar answered Oct 08 '22 12:10

David Medenjak