Hussnain Azam
Hussnain Azam

Reputation: 358

Scroll nested RecyclerView programmatically to a position

I know how to programmatically scroll a recyclerview to a particular position. But my problem is i have a recyclerview with vertical linearLayout that has another child recyclerview gridlayout with on its each row. Now when i scroll parent recyclerview programmatically it doesn't scroll to given position. But if a remove child recyclerview from it then it scrolls without any issue. This is what i have tried and everything worked for single recyclerview having no child recyclerview in its rows.

card_recyclerView.getLayoutManager().scrollToPosition(position)
card_recyclerView.smoothScrollToPosition(position);
card_recyclerView.getLayoutManager().scrollToPositionWithOffset(position, 20);

My main recyclerview

<androidx.recyclerview.widget.RecyclerView
                            android:id="@+id/card_recyclerView"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginRight="5dp"
                            android:clipToPadding="false"
                            android:layout_marginLeft="5dp"
                            android:background="#ffffff"
                            android:layout_weight="1"
                            />

Main recyclerview row item

                            <androidx.recyclerview.widget.RecyclerView
                            android:id="@+id/cards_recycler_adapter"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_below="@+id/layout_see_more_top"/>

Upvotes: 5

Views: 1485

Answers (1)

Sina
Sina

Reputation: 2883

I just created your view without any problem. I managed to scroll with only

card_recyclerView.getLayoutManager().scrollToPosition(position)
card_recyclerView.smoothScrollToPosition(position);

This is my code for viewholder of the first adapter:

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    ViewHolder(View itemView) {
        super(itemView);
        RecyclerView recyclerView = itemView.findViewById(R.id.recyclerView2);
        recyclerView.setAdapter(new TestAdapter2(itemView.getContext(), mData));
        GridLayoutManager linearLayoutManager = new GridLayoutManager(itemView.getContext(), 3);
        recyclerView.setLayoutManager(linearLayoutManager);
    }
}

If you still have problems please provide the code for adapters and maybe the xml for rows.

Upvotes: 2

Related Questions