Android Squared CardView

  1. Home
  2. chevron_right
  3. Solutions
  4. chevron_right
  5. Android Squared CardView

Recently, I had to add a perfect square CardView and I wanted to achieve this without hardcoding its width and height. I happily discovered the power of ConstraintLayout and this is how I managed to create a perfect square which should work on every dimension.

<?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="wrap_content">
    <androidx.cardview.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="8dp"
        app:cardElevation="8dp"
        app:contentPadding="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="1:1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:orientation="vertical">
            <ImageView
                android:id="@+id/category_image"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center" />
            <TextView
                android:id="@+id/category_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:gravity="center_horizontal"/>
        </LinearLayout>
    </androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>

In my project I created a RecyclerView with 2 columns, and this is how the result looks like.

The main attributes to achieve the square positioned like in the above image, were these:

  • app:layout_constraintDimensionRatio=”1:1″
  • wrap_content on the ConstraintLayout
  • on the cardView the constraints are set to parent and the width and height to 0 (match_constraint)

Note: The red background is set on the recyclerView’s background.