Search code examples
androidandroid-recyclerviewonscrolllistener

In nested RecyclerView child's onScrollListener not getting trigerred


I was trying to achieve a layout where there is carousel at the top and below it is a grid layout of images. The activity has a RecyclerView and the item of that RecyclerView(MainRV) itself is another RecyclerView(ChildRV). I made the first child of the MainRV use a LinearlayoutManager with Horizontal Scroll. The second child is using a GridLayoutManager. The ChildRV renders actual items.

The problem is, I want to implement lazy loading for the second child of the MainRV (grid view). But, When I try to add onScrollListener to the child, it is not getting triggered.

What I have tried:

I tried setting setNestedScrollingEnabled on both MainRV and ChildRV. Still it did not trigger the onScrollListener.

I implemented the onScrollListener on the MainRV and tried to get the second child after scroll state becomes IDLE. But when I call the findLastVisibleItemPosition() on the gridLayoutManager, it gives the position of the last item even though I am at the top of the grid view. Below is the snippet of the onScrollListener

mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        if(newState == RecyclerView.SCROLL_STATE_IDLE) {

            RecyclerView recyclerView1 = (RecyclerView) recyclerView.getChildAt(1);
            GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView1.getLayoutManager();

            Log.e("Scrolled activity pos", "" + gridLayoutManager.findLastVisibleItemPosition());
        }
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
    }
});

The output of the above code gives the position of the last item which is 49 in my case.

Any help or suggestion would be greatly appreciated.


Solution

  • The issue here was resolved when I removed the "static" qualifier on the ViewHolder for the nested RecyclerView. For some reason, the reuse of the view to bind the list items was giving out false results when looking for the lastVisiblItem. If someone can explain why then I would be really greatful. I could not figure it out.