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 w
You can find the first and last visible children of the recycle view and check if the view you're looking for is in the range:
var visibleChild: View = rv.getChildAt(0)
val firstChild: Int = rv.getChildAdapterPosition(visibleChild)
visibleChild = rv.getChildAt(rv.childCount - 1)
val lastChild: Int = rv.getChildAdapterPosition(visibleChild)
println("first visible child is: $firstChild")
println("last visible child is: $lastChild")
Following Linear / Grid LayoutManager
methods can be used to check which items are visible
int findFirstVisibleItemPosition();
int findLastVisibleItemPosition();
int findFirstCompletelyVisibleItemPosition();
int findLastCompletelyVisibleItemPosition();
and if you want to track is item visible on screen
for some threshold then you can refer to the following blog.
https://proandroiddev.com/detecting-list-items-perceived-by-user-8f164dfb1d05
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.