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  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) {

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

    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);

                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=""
    android:layout_width="match_parent" android:layout_height="match_parent">




And it should look like this screenshot: