Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the same layout_weight leading to different widths for Android ImageButton and Button?

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>
like image 515
SnoopDougg Avatar asked Jan 11 '17 03:01

SnoopDougg


1 Answers

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.

like image 63
Ted Hopp Avatar answered Oct 22 '22 00:10

Ted Hopp