可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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:
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.
回答3:
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.
回答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.