在 RecyclerView 中获取可见项目 [英] Get visible items in RecyclerView

查看:56
本文介绍了在 RecyclerView 中获取可见项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道当前在我的 RecyclerView 中显示了哪些元素.没有等效于 OnScrollListener.onScroll(...) 方法在 ListViews 上.我尝试使用 View.getGlobalVisibleRect(...),但是这个 hack 太丑了,而且并不总是有效.

I need to know which elements are currently displayed in my RecyclerView. There is no equivalent to the OnScrollListener.onScroll(...) method on ListViews. I tried to work with View.getGlobalVisibleRect(...), but that hack is too ugly and does not always work too.

有人有什么想法吗?

推荐答案

第一个/最后一个可见的孩子取决于 LayoutManager.如果您使用 LinearLayoutManagerGridLayoutManager,则可以使用

First / last visible child depends on the LayoutManager. If you are using LinearLayoutManager or GridLayoutManager, you can use

int findFirstVisibleItemPosition();
int findFirstCompletelyVisibleItemPosition();
int findLastVisibleItemPosition();
int findLastCompletelyVisibleItemPosition();

例如:

GridLayoutManager layoutManager = ((GridLayoutManager)mRecyclerView.getLayoutManager());
int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();

对于LinearLayoutManager,第一个/最后一个取决于适配器顺序.不要从 RecyclerView 查询孩子;LayoutManager 可能更喜欢布局比可见缓存更多的项目.

For LinearLayoutManager, first/last depends on the adapter ordering. Don't query children from RecyclerView; LayoutManager may prefer to layout more items than visible for caching.

这篇关于在 RecyclerView 中获取可见项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆