Search code examples
javaandroid-studioandroid-recyclerviewonscrolllistener

RecyclerView.addOnScrollListener() not getting called when scrolling down


My app uses a RecyclerView to load and display items in a list, 20 at a time. I attached a scroll listener like so:

        recentItemArrayAdapter = new RecentCommentsAdapter(this, activity, itemList);
        recent_comments_view = findViewById(R.id.recent_comments_view);
        recent_comments_view.setAdapter(recentItemArrayAdapter);
        recent_comments_view.addItemDecoration(new DividerItemDecoration(activity,
            DividerItemDecoration.VERTICAL));
        recent_comments_view.setLayoutManager(new LinearLayoutManager(this));
       // Add the scroll listener to RecyclerView
        recent_comments_view.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();

            if (layoutManager != null && 
                layoutManager.findLastCompletelyVisibleItemPosition() == 
                itemList.size() - 1) {
                // End of the list is reached, load more data
                fetchNextBatch(documents.get(documents.size() -1));
            }
        }
    });

When I scroll down, I expect the listener to be called, but it doesn't. FWIW, I'm using Android Studio Flamingo version 2022.2.1 Patch 1 on a Linux laptop.


Solution

  • It turned out I had code TWO onScrollListeners: one in onCreate() in the activity and the other in a dialog window. The one in the activity was getting called, but I only noticed it when I accidentally tried to scroll the main page. I removed the onScrollListener() in onCreate() and the listener in the dialog window is getting called, as expected.