How to implement load more recyclerview in android

I found an answer here that, I believe, is much better than most I've seen on SO and elsewhere.

The idea is simple: in onScrolled in your RecyclerView's ScrollListener, check if the last completely visible item is the last item in your data set.

        if(llm.findLastCompletelyVisibleItemPosition() == data.length() -1){
            //bottom of list!
            loadMoreData();
        }

This happens with a method in the LinearLayoutManager. Calling LinearLayoutManager#findLastCompletelyVisibleItemPosition() can comparing it to the position of the last item in your dataset let's you know when you can load more.

I haven't tried this for the GridLayoutManager.

UPDATE

LinearLayoutManager#findLastVisibleItemPosition() is a better alternative to LinearLayoutManager#findLastCompletelyVisibleItemPosition(), especially when your items are longer than the window height.


Check do you currently have items to scroll down -

if (! recyclerView.canScrollVertically(1))

If yes - load more items, for example, using HTTP client.

Full code:

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (! recyclerView.canScrollVertically(1)){ //1 for down
                    loadMore();
                }
            }
        });

Try this....

  static boolean loadmore=true;
  LinearLayoutManager layoutManager = ((LinearLayoutManager)recyclerView.getLayoutManager());
   recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            // super.onScrolled(recyclerView, dx, dy);
            int lastVisiblePosition = layoutManager.findLastVisibleItemPosition();
            if (lastVisiblePosition == recyclerView.getChildCount()) {
                if (loadmore) {
                    loadmore = false;
                   method();
                }
            }
        }
    });


  private void method(){
      loadmore=true;
  }

In Kotlin you can use the below code snippet.

    recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            if(!recyclerView.canScrollVertically(1)) {
                // LOAD MORE
            }
        }
    })