Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 384
SecStone Avatar asked Mar 24 '12 14:03

SecStone


2 Answers

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.

like image 100
Jason Robinson Avatar answered Oct 07 '22 01:10

Jason Robinson


try adding

adjustViewBounds="true"

to the ImageButton, that should clip the excess width


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

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

    <ImageButton
        android:id="@+id/btSet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:src="@drawable/pin" />
</LinearLayout>
like image 44
Mark Pazon Avatar answered Oct 07 '22 01:10

Mark Pazon