How do I keep the aspect ratio on image buttons in android?

   <LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:id="@+id/layoutButtons">

     <com.package.SquareButton         
        android:layout_height="fill_parent"
        android:layout_width="0dip"          
        android:layout_weight="1"

        <ImageView
        android:id="@+id/box1"
        android:layout_gravity="center"
        android:adjustViewBounds="true"
        android:scaleType="centerInside"
        android:layout_height="wrap_content"
        android:layout_width="0dp"          
        android:layout_weight="1" 
        android:layout_marginLeft="5dp" 
        android:layout_marginRight="5dp"/>

      </com.package.SquareButton>

      <com.package.SquareButton         
        android:layout_height="fill_parent"
        android:layout_width="0dip"          
        android:layout_weight="1"

        <ImageView
        android:id="@+id/box2"
        android:layout_gravity="center"
        android:adjustViewBounds="true"
        android:scaleType="centerInside"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"          
        android:layout_marginLeft="5dp" 
        android:layout_marginRight="5dp"/>

</com.package.SquareButton>

   .........          
 </LinearLayout>

And then add this custom button class:

public class SquareButton extends LinearLayout {

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

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

    // This is used to make square buttons.
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }
}

Leave a Comment