Recently, I had to add a perfect squared CardView and I wanted to achieve this without hardcoding its width and height. I happily discovered the power of ConstraintLayout. And so this is how I managed to create a perfect square which should work on every dimension.
Heres some sample code that I used to create that square from a CardView using a ConstraintLayout.
<?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 (btw, maybe you want to see this post about 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: I’ve set the red color on the recyclerView’s background. It has nothing to do with this but it just highlights better the cards. :)
Now, this might not be the best solution for every case. That’s up to you to decide where to use it or where to go with some computed width and height. But it is indeed good to know alternatives and options for when the time comes to make use of the proper one.
If you have any suggestions or comments/improvements over this squared CardView approach, please feel free to leave it in the comments section bellow. :)