How to adjust the size of a RecyclerView to show the first 3 elements and then scroll to see the rest of the elements?

Viewed 406

I have a RecyclerView in one layout and in another layout the layout of the element that is added to it.

What I want to do is that in the RecyclerView only the first three elements are seen and then to see the next ones you have to scroll.

That is, if there is one item, the size of the RecyclerView is equal to the size of one item. If it contains two, let the size fit those two items. The same with three but from the three elements, you need to scroll. I have tried using LinearLayoutManager but I see all the added elements.

1 Answers

I'm not sure if there are better ways to do this, but I found one trick on SO that helped me with this - wrap your recycler view with ConstraintLayout and the set on RecyclerView - "layout_constraintHeight_max":

<androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/Id_const_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/Id_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constrainedHeight="true"
        app:layout_constraintBottom_toBottomOf="@+id/Id_const_layout"
        app:layout_constraintEnd_toEndOf="@+id/Id_const_layout"
        app:layout_constraintHeight_max="200dp"
        tools:listitem="@layout/YOUR_ITEM" />

 </androidx.constraintlayout.widget.ConstraintLayout>

It worked on my project with height of 200, adjust it accordingly to your item height*3.

Related