Home » Android » android – How to make a grid layout of CardViews with variable height?

android – How to make a grid layout of CardViews with variable height?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have multiple CardView‘s defined in XML as:

<android.support.v7.widget.CardView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    card_view:cardPreventCornerOverlap="false"
    card_view:cardCornerRadius="4dp">
    <LinearLayout
        android:layout_width="wrap_content"
        android:orientation="vertical"
        android:layout_height="wrap_content">
        <TextView
            android:textSize="@dimen/abc_text_size_title_material"
            android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
</android.support.v7.widget.CardView>

For phones, I have wrapped the multiple CardView‘s in a vertical LinearLayout:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

For tablets, I would like to use a grid layout instead, similar to the design used in the Material Design specs, see image here.

What’s the best ViewGroup to use to make the grid layout? The cards are of variable height, and have static content.

GridLayout can’t be used, because the cards are of variable height.

How to&Answers:

I had faced this same problem some time back. Yes, you can not use a GridLayout as your Cards are of variable size. So what you are looking for StaggeredGridView which allows its items to have variable sizes.

You can do either of the following :-

1) You can use this or this library. They are very simple to use. I have used both and I can assure you that they do their work perfectly.

2) You can try the RecyclerView.StaggeredGridLayoutManager from Google.

A sample code would look somethings like this,

RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
    recyclerView.setAdapter(adapter);

Hope it helps you.

Answer:

For tablets you can use 2 LinearLayouts.