6

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?

Spaci Tron
  • 383
  • 1
  • 4
  • 11

2 Answers2

15

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.

David Medenjak
  • 33,993
  • 14
  • 106
  • 134
0

After researching a lot of sites and can not find a solution for using findLastVisibleItemPosition method. I used another solution and answered it in there:
Can't find RecyclerView visible item position inside NestedScrollView

NhatVM
  • 1,964
  • 17
  • 25