Get visible items in RecyclerView

匿名 (未验证) 提交于 2019-12-03 02:10:02

问题:

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.

Someone any ideas?

回答1:

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(); 

For example:

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

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.



回答2:

Finally, I founded a solution for know if the current item is visible, from the onBindViewHolder event in the adapter.

The key is the method isViewPartiallyVisible from LayoutManager.

In your adapter, you can get de LayoutManager from the recyclerView, which you can get from the onAttachedToRecyclerView event.



回答3:

You can use recyclerView.getChildAt() to get each visible child, and setting some tag convertview.setTag(index) on these view in adapter code will help you to relate it with adapter data.



回答4:

For StaggeredGridLayoutManager do this:

RecyclerView rv = findViewById(...); StaggeredGridLayoutManager lm = new StaggeredGridLayoutManager(...); rv.setLayoutManager(lm); 

And to get visible item views:

int[] viewsIds = lm.findFirstCompletelyVisibleItemPositions(null); ViewHolder firstViewHolder = rvPlantios.findViewHolderForLayoutPosition(viewsIds[0]); View itemView = viewHolder.itemView; 

Remember to check if it is empty.



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