NestedScrollView中的RecyclerView无法提供正确的可见项位置 [英] RecyclerView inside NestedScrollView does not give correct visible item position
问题描述
我在NestedScrollView
内有一个RecyclerView
,并且我试图在使用滚动事件期间获取最后一个可见列表项的位置.以下代码使我能够可靠地检测滚动事件:
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()
}
但是,问题在于,无论实际上是否在这里,lastVisiblePosition
总是最终成为列表中的最后一项.我哪里出问题了?
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?
推荐答案
如果您将RecyclerView
放在可滚动容器中-在您的情况下 NestedScrollView
基本上会变成花哨的LinearLayout
,膨胀并显示一次所有的项目.您获得的第一个和最后一个项目是第一个和最后一个可见的项目,因为它们对RecyclerView来说是这样.所有项目都被夸大并添加,因此所有这些项目都在可滚动视图内显示在屏幕上".
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.
简单的解决方案是不将RecyclerView嵌套在NestedScrollView中. RecyclerView可以滚动,因此您也可以将所需的任何页眉或页脚放入RecyclerView中.嵌套可滚动视图总是有弊端,您应该尽可能避免使用它.
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.
这篇关于NestedScrollView中的RecyclerView无法提供正确的可见项位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!