Skip to content

Instantly share code, notes, and snippets.

@vxhviet
Created January 16, 2020 06:50
Show Gist options
  • Save vxhviet/faa230cadee404e80ca6a8866247a988 to your computer and use it in GitHub Desktop.
Save vxhviet/faa230cadee404e80ca6a8866247a988 to your computer and use it in GitHub Desktop.

How to make RecyclerView wrap_content

SOURCE, SOURCE

This works for these set up:

api 'androidx.constraintlayout:constraintlayout:2.0.0-beta4'
implementation "androidx.recyclerview:recyclerview:1.2.0-alpha01"

In order to make a short RecyclerView wrap_content in a ScrollView with ConstraintLayout we need to:

1. Change ScrollView to NestedScrollView

<androidx.core.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/fcnd_root_sv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="none"
    android:fillViewport="true"> // this is optional, fo fix the case when the child layout doesn't fill the view
    
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        
        <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/lcnd_past_medical_history_list_rc"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constrainedHeight="true"  // for wrap_content in ConstraintLayout to work, we will need this
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/lcnd_view_all_history_btn" />
        
    </androidx.constraintlayout.widget.ConstraintLayout>
    
</androidx.core.widget.NestedScrollView>

2. Keep ScrollView, but wrap RecyclerView inside a RelativeLayout

<ScrollView>
  </androidx.constraintlayout.widget.ConstraintLayout>
    <RelativeLayout>
      <RecyclerView>
    </RelativeLayout>
  </androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment