Android Tutorial – Square Layout

For the latest app I’ve developed, I needed to use squared layout. It would be easy with fixed size – I would put the height (width) dimension into the dimens.xml file and it would work. However that wasn’t what I needed.

The goal is to have layout which will be squared with width (or height) set up to match_parent.

And because this is not part of the Android SDK, we are going to create it. Firstly create new Java class in your project. I store these files in src/main/java/com.example.something/tools but you are free to choose your own destination 😉 Name it SquareLayout.java.  This file will be extending the LinearLayout, so I will just paste the complete code, it’s pretty simple to understand.

public class SquareLayout extends LinearLayout {

    public SquareLayout(Context context) {
        super(context);
    }

    public SquareLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);

        // this is the scale between width & height, for square should be == 1
        int scale = 1;

        if (width > (int)(scale * height + 0.5)) {
            width = (int)(scale * height + 0.5);
        } else {
            height = (int)(width / scale + 0.5);
        }

        super.onMeasure(
                MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)
        );
    }
}

Well done. Now we can use this new layout in your layout files. And it works like this (don’t forget to change com.example.something to your namespace):

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_margin="60dp"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <com.example.something.SquareLayout
        android:background="@color/pink"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        </com.example.something.SquareLayout>

</RelativeLayout>

And it should look like this screenshot:

android-square-layout-tutorial-example

Leave a Reply

Your email address will not be published. Required fields are marked *