I have been often told to use 0dp on views while using weight in XML like this :
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/a1"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:text="1" />
</LinearLayout>
but there is a problem with this code which is when i use a view like Button, i can't force it to take the exact weight im giving to it.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/a1"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="25"
android:text="1" />
<Button
android:id="@+id/a2"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:text="2" />
</LinearLayout>
in the code written above, the 2nd button will never be exactly 1/26 because the button itself has some margin and padding by default.
but when i use match_parent for their height, it forces them to be exactly 1/26 and it works perfectly.
but i can't understand why the 1st button gets to be 1/26 and it seems like they exchange their weight, and it gets more complicated when i use 3 views.
- is there a better way of achieving this goal ?
- and why weight acts different while using match_parent ?
the spacing in the
Buttonis not padding or margin, but it was a background. if you want to remove the spacing you should change the background of theButtonit is recommended to use
android:layout_height="0dp"because the docs oflayout_weightsaid :It said "extra space" not "space". So the right height should be 0dp + "extra space calculated"
here some sample code
and the result