RecyclerView inside NestedScrollView does not give correct visible item position

孤街浪徒 提交于 2019-12-19 10:17:37

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/48428793/recyclerview-inside-nestedscrollview-does-not-give-correct-visible-item-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!