androidandroid-recyclerviewandroid-linearlayoutandroid-nestedscrollviewandroid-wrap-content

RecyclerView wrap_content not working on API 23 and above


I have a layout with a RecyclerView inside a LinearLayout which is also inside a custom NestedScrollView. In api 21 and 22 the layout looks like it's supposed to showing all the elements of the RecyclerView, but in api 23 and above only one or two items are shown leaving the rest of the screen blank. I know the point of RecyclerView is to not use wrap_content, but it is my understanding that you can.

I noticed that when the views above the RecyclerView are visible, wrap_content on the recyclerview works correctly, but in the particular case I'm having the issue those views are all programmatically set to gone, so it seems to have something to do with that. So I'm not sure what to do about it since those views are supposed to be gone. Is this an android sdk bug I can't get around?

<CustomNestedScrollView
                    android:id="@+id/editProfileScroll"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:scrollbars="vertical">

                    <LinearLayout
                        android:id="@+id/editProfileMainContainer"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="@dimen/material_baseline_grid_10x"
                        android:orientation="vertical">

                        <!-- More code: TextViews and TextViews inside LinearLayouts -->

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

                    </LinearLayout>

                </CustomNestedScrollView>

Solution

  • Try using a RelativeLayout instead of a LinearLayout.


    With LinearLayout you will have to set

    android:orientation="vertical"
    android:weight_sum="3"
    

    and in each element you will have to add android:layout_weight="1".

    By doing the above it will space 3 items evenly across the vertical axis.