I'm getting some weird behavior in my LinearLayout when I try to set regular Buttons and an ImageButton to the same layout_weight
. The image button's android:src
resource is extrememly small and fits well inside the ImageButton without any problems. Even though their widths should be identical, for some reason the ImageButton's width is about 2/3rds the size of the rest of the normal buttons. If I multiply the ImageButton's layout_weight
by 10, its much closer to the right size, but why isn't this working?
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight="1">
<Button
android:id="@+id/clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/clear"/>
<Button
android:id="@+id/left_paren"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/left_paren"/>
<Button
android:id="@+id/right_paren"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/right_paren"/>
<ImageButton
android:id="@+id/backspace"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:adjustViewBounds="true"
android:contentDescription="@string/backspace"
android:src="@drawable/backspace"/>
</LinearLayout>
You need to set android:layout_width="0dp"
for all buttons that should be the same width. (More precisely, you need to set the same layout_width
for all those buttons and 0dp
is the conventional width to use. When using equal weights, as long as there's still extra space to distribute, the actual width you use isn't relevant to the result.) The layout_weight
only determines how the remaining space is allocated after the buttons take up their assigned widths. So if they start out unequal (which they will with widths of wrap_content
), they remain different after their weights are taken into account.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With