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

前端 未结 5 1938
自闭症患者
自闭症患者 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:53

    If someone stumble across this post this is a quick and simple tutorial on how to do it:

    All you need to do is:

    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }
    
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int visibleItemCount        = lm.getChildCount();
            int totalItemCount          = lm.getItemCount();
            int firstVisibleItemPosition= lm.findFirstVisibleItemPosition();
    
            // Load more if we have reach the end to the recyclerView
            if ( (visibleItemCount + firstVisibleItemPosition) >= totalItemCount && firstVisibleItemPosition >= 0) {
                loadMoreItems();
            }
        }
    });
    

    Then your loadMoreItems() should look something like this:

    private void loadMoreItems() {
        // init offset=0 the frist time and increase the offset + the PAGE_SIZE when loading more items
        queryOffset = queryOffset + PAGE_SIZE;
        // HERE YOU LOAD the next batch of items
        List newItems = loadItems(queryOffset, PAGE_SIZE);
    
        if (newItems.size() > 0) {
            items.addAll(newItems);
            adapter.notifyDataSetChanged();
        }
    }
    

提交回复
热议问题