How To Make a Square Layout In Android Example

Please follow and like us:

Make a Square Layout In Android

If you are searching for making layout’s height same as layout’s width or making GridView or ListView  items square then you are at the right place.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.nkdroid.sampleapp.MainActivity">

    <com.nkdroid.sampleapp.CustomSquareLayout
        android:id="@+id/frame"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_gravity="center"

        android:background="#ddd">
        <ImageView
            android:padding="16dp"
            android:scaleType="fitXY"
            android:src="@drawable/marshmallow"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />


        </com.nkdroid.sampleapp.CustomSquareLayout>

</LinearLayout>

CustomSquareLayout.java

package com.nkdroid.sampleapp;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;


public class CustomSquareLayout extends RelativeLayout {
	private float heightRatio;
	private int maxHeight;
	
	
	public CustomSquareLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		heightRatio = attrs.getAttributeFloatValue(null, "heightRatio", 1.0f);
		maxHeight = -1;
	}
	
	
	public void setMaxHeight(int maxHeight) {
		this.maxHeight = maxHeight;
	}
	@Override
	protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
		// We have to manually resize the child views to match the parent.
		for (int i = 0; i < getChildCount(); i++) {
			final View child = getChildAt(i);
			final LayoutParams params = (LayoutParams)child.getLayoutParams();
			
			if (params.height == LayoutParams.MATCH_PARENT) {
				params.height = bottom - top;
			}
		}
		super.onLayout(changed, left, top, right, bottom);
	}
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		final int width = MeasureSpec.getSize(widthMeasureSpec);
		int height = (int)Math.ceil(this.heightRatio * (float)width);
		if (maxHeight != -1 && height > maxHeight) height = maxHeight;
		setMeasuredDimension(width, height);
	}
}

 

 

Hope you liked our simple tutorial of “Make a Square Layout In Android“.

Happy Coding 🙂

nirav kalola