Get visible items in RecyclerView

前端 未结 9 1951
礼貌的吻别
礼貌的吻别 2020-11-22 07:17

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

相关标签:
9条回答
  • 2020-11-22 08:12

    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")
    
    0 讨论(0)
  • 2020-11-22 08:18

    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

    0 讨论(0)
  • 2020-11-22 08:19

    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.

    0 讨论(0)
提交回复
热议问题