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?

4
  • set recylcerview.setnestedscrolllingenabled(false); Commented Jan 24, 2018 at 17:57
  • 1
    I did that. Makes no difference. Commented Jan 24, 2018 at 18:07
  • What is the height of your recyclerview? Commented Jan 24, 2018 at 18:15
  • I tried both wrap_content and match_parent. First visible item is always the first list item and last is always the last item. Commented Jan 24, 2018 at 18:28

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

So, there is no way to stop recyclerview from inflating all items at a time when it is inside nestedscrollview?
what if we want to implement collapsing app bar @David
@ParthAnjaria then you use a CoordinatorLayout with the AppBarLayout & RecyclerView. There should be plenty of examples online
what if I want to add swipe to refresh with recyclerview? @DavidMedenjak
@NevilGhelani SwipeRefreshLayout doesn't interfere with RVs recycling
|
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.