我需要知道哪些元素目前显示在我的RecyclerView。ListViews上没有与OnScrollListener.onScroll(…)方法等价的方法。我试图与view . getglobalvisibl勃起(…)工作,但黑客是太丑陋,并不总是工作太。
有人有什么想法吗?
我需要知道哪些元素目前显示在我的RecyclerView。ListViews上没有与OnScrollListener.onScroll(…)方法等价的方法。我试图与view . getglobalvisibl勃起(…)工作,但黑客是太丑陋,并不总是工作太。
有人有什么想法吗?
当前回答
最后,我找到了一个解决方案,从适配器中的onBindViewHolder事件了解当前项是否可见。
关键是来自LayoutManager的isViewPartiallyVisible方法。
在您的适配器中,您可以从RecyclerView中获得LayoutManager,它作为参数从onAttachedToRecyclerView事件中获得。
其他回答
您可以使用recyclerView.getChildAt()来获取每个可见的子视图,并在适配器代码中对这些视图设置一些convertview.setTag(index)标记将帮助您将其与适配器数据关联起来。
最后,我找到了一个解决方案,从适配器中的onBindViewHolder事件了解当前项是否可见。
关键是来自LayoutManager的isViewPartiallyVisible方法。
在您的适配器中,您可以从RecyclerView中获得LayoutManager,它作为参数从onAttachedToRecyclerView事件中获得。
对于那些在Kotlin中寻找答案的人:
fun getVisibleItem(recyclerView : RecyclerView) {
recyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
if(newState == RecyclerView.SCROLL_STATE_IDLE) {
val index = (recyclerView.layoutManager.findFirstVisibleItemPosition
//use this index for any operation you want to perform on the item visible on screen. eg. log(arrayList[index])
}
}
})
}
您可以根据您的用例探索获取该职位的其他方法。
int findFirstCompletelyVisibleItemPosition()
int findLastVisibleItemPosition()
int findLastCompletelyVisibleItemPosition()
上面的每个答案都是正确的,我也想添加一个快照从我的工作代码。
recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
// Some code when initially scrollState changes
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// Some code while the list is scrolling
LinearLayoutManager lManager = (LinearLayoutManager) recyclerView.getLayoutManager();
int firstElementPosition = lManager.findFirstVisibleItemPosition();
}
});
Addendum: The proposed functions findLast...Position() do not work correctly in a scenario with a collapsing toolbar while the toolbar is expanded. It seems that the recycler view has a fixed height, and while the toolbar is expanded, the recycler is moved down, partially out of the screen. As a consequence the results of the proposed functions are too high. Example: The last visible item is told to be #9, but in fact item #7 is the last one that is on screen. This behaviour is also the reason why my view often failed to scroll to the correct position, i.e. scrollToPosition() did not work correctly (I finally collapsed the toolbar programmatically).