Android Studio ConstraintLayout GuideLines on Button while keeping it square

I am trying to keep all my views constraint to guidelines so that it'll always be relative and not mess up on different screens.

I ran into a problem where I have a button(using a background of an image with no text to control button size). That I'd like to keep square WHILE ALSO keep within guidelines... but of course, it cannot be that way since unless the resolution is square(which it never is) you cannot always have it square within guidelines.

Is there a way to enforce its size to be square while also keeping it somewhat relative and resizing based on screen size?


After experimenting, I think I got it. The key is the layout_constraintDimensionRatio command.

In this layout, I have a button (using the pause icon as the background--it's easy to see if it's square or not) without text. It is constrained to two gridlines that are 30% away from the top left corner. You can of course modify as needed.

The width of the button is set to wrap_content, while the height is set to 0dp, which denotes use the constraints.

But the big key is setting the layout_constraintDimensionRatio="H,1:1". This forces the ratio to always be square.

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        app:layout_constraintDimensionRatio="H,1:1"
        android:background="@android:drawable/ic_media_pause"
        app:layout_constraintStart_toStartOf="@+id/vert_guide"
        app:layout_constraintTop_toTopOf="@+id/horiz_guide"
        />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/vert_guide"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="30pt" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/horiz_guide"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_begin="30pt" />
</androidx.constraintlayout.widget.ConstraintLayout>

Let me know how this works. I haven't thoroughly tested this, so it may not work in every situation.