SquareLayout

Average: 5 (1 vote)

This is a subclass of android.widget.Button that forces the width and height to be the same. The dimensions of the button are set to the smallest of the dimensions.

Layout source: 
// SquareButton.Java
 
package com.antiyes.example.Views;
 
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;
 
public class SquareButton extends Button
{
 
	public SquareButton(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
	}
 
	public SquareButton(Context context, AttributeSet attrs)
	{
		super(context, attrs);
	}
 
	public SquareButton(Context context)
	{
		super(context);
	}
 
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
 
	    //Get canvas width and height
	    int w = MeasureSpec.getSize(widthMeasureSpec);
	    int h = MeasureSpec.getSize(heightMeasureSpec);
 
	    w = Math.min(w, h);
	    h = w;
 
	    setMeasuredDimension(w, h);
	}
 
 
}
<!-- main.xml -->
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical" >
 
    <com.antiyes.example.Views.SquareButton
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_margin="15dip"
        android:layout_weight="1"
        android:text="Button 2" />
 
    <com.antiyes.example.Views.SquareButton
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_margin="15dip"
        android:layout_weight="1"
        android:text="Button 1" />
 
</LinearLayout>