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?
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.
NestedScrollView is used when there is a need for a scrolling view inside another scrolling 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With