Search code examples
androidoverflowcardview

Android GridLayout single CardView takes all screen


I'm want to implement a 2x2 GridLayout so I can show 4 Card Views. My problem is a single Card View is taking all the space. When I add the second one (row 0, column 1) it is positioned out of the screen (on the right).

This is my layout code

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<androidx.gridlayout.widget.GridLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:columnCount="2"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:rowCount="2">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_row="0"
        app:layout_column="0" />

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_row="0"
        app:layout_column="1" />
</androidx.gridlayout.widget.GridLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Solution

  • both CardViews match the width of the parent, that's why, you only see one you can change it like this

    android:layout_width="wrap_content"
    app:layout_columnWeight="1"
    

    using app:layout_columnWeight will ensure both cards have the same width regardless of their content