How can I identify that RecyclerView's last item is visible on screen?

前端 未结 5 1895
自闭症患者
自闭症患者 2021-01-31 19:18

I have one RecyclerView and I added list of data into the RecyclerView. I wanted to add more data in list, when last RecyclerView item is

5条回答
  •  终归单人心
    2021-01-31 19:57

    One option would involve editing your LayoutManager. The idea here is to find the position of the last visible item. If that position is equal to the last item of your dataset, then you should trigger a reload.

        @Override
        public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
    
            final int result = super.scrollVerticallyBy(dy, recycler, state);
    
            if (findLastVisibleItemPosition() == mData.length - 1) {
               loadMoreData();
            } 
    
            return result;
    
        }
    
        @Override
        public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
            super.onLayoutChildren(recycler, state);
    
            if (findLastVisibleItemPosition() == mData.length - 1) {
               loadMoreData();
            } 
        }
    

    Alternatively, you could do this via your adapter's onBindViewHolder method, although this is admittedly a bit of a "hack":

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (position == mData.length - 1) {
                // load more data here.
            }
    
            /// binding logic
        }
    

    3rd option would be to add an OnScrollListener to the RecyclerView. @velval's answer on this page explains this well.

    Regardless which option you go for, you should also include code to prevent the data load logic from triggering too many times (e.g., before the previous request to fetch more data completes and returns new data).

提交回复
热议问题