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]):
<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:
Just ran into something like this and the other suggestions didn't help. What did help was setting the padding in the ImageButton:
Besides that, I didn't touch the original layout. The button became square on the 3 emulators that I tested (3.2, 4.4.2, 5.1)
as you want your
ImageButton
is stretchable & exactly as wide as it's long, its better to useNinePatch Image
. you may find help form here Draw 9-patch & How does Android’s nine-patch tool work ?Try this, I think this should work:
Explaination:
centerInside
will assure that the image will scale proportionally within the bounds of theImageButton
.adjustViewBounds="true"
will...well, adjust the view's bounds, if the image needed to be scaled.Simply use the weightSum to devide the size of controls accordingly...
Hope it will help you.
I had the same problem. I was trying to create something that looked like this:
But what I was getting was this:
The
ImageButton
was getting stretched horizontally.All the top answers didn't work for me. But I noticed people mentioning
layout_weight
and just looked it up out of curiosity and found the following on Android docs:So basically, if you set the
layout_width
to be 0 for an element, it'll appear according to the dimensions of its content.If you set it to anything else, the element will fight for extra space in the parent element that contains it; with more weighted elements taking up more space.
So, when I set
layout_width = 0
for bothTextView
andImageButton
in my example, neither of them takes up any extra space and they both huddle up to the left.But when I set it to 1 for
TextView
and 0 forImageButton
, theImageButton
doesn't take any more space than required by its content; while theTextView
takes up all the extra space and pushesImageButton
to the right.Just the way I want it.
Initially, what had happened was both the elements were set to have a default
layout_weight
of 1 and hence both were equally competing for the extra space.You Can resize the Image button using px... like below...