ImageButton: Force square icon (height = WRAP_CONTENT, width = ?)

SecStone picture SecStone · Mar 24, 2012 · Viewed 9.7k times · Source

In my horizontal LinearLayout I have a TextEdit and an ImageButton. The ImageButton is as high as the TextEdit.

I'd like that the ImageButton is exactly as wide as it's long.

At the moment it looks like the width of the ImageButton is like when there is no scaling (ImageButton width [px] = unscaled drawable width [px]):

example

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <EditText
        android:id="@+id/txtName"
        android:layout_width="1dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <ImageButton
        android:id="@+id/btSet"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:scaleType="fitEnd"
        android:src="@drawable/pin2" />

</LinearLayout>

How it should look like:

objective

Answer

Jason Robinson picture Jason Robinson · Apr 5, 2012

Try this, I think this should work:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:orientation="horizontal" >

    <ImageButton
        android:id="@+id/btSet"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:scaleType="centerInside"
        android:adjustViewBounds="true"
        android:src="@drawable/pin2" />

    <EditText
        android:id="@+id/txtName"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_toLeftOf="@id/btSet" />

</RelativeLayout>

Explaination: centerInside will assure that the image will scale proportionally within the bounds of the ImageButton. adjustViewBounds="true" will...well, adjust the view's bounds, if the image needed to be scaled.