Linear Layout and weight in Android

3 things to remember:

  • set the android:layout_width of the children to “0dp”
  • set the android:weightSum of the parent
    (edit: as Jason Moore noticed, this attribute is optional, because by default it is set to the children’s layout_weight sum)
  • set the android:layout_weight of each child proportionally (e.g. weightSum=”5″, three children: layout_weight=”1″, layout_weight=”3″, layout_weight=”1″)

Example:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:weightSum="5">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:text="2" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="3" />

</LinearLayout>

And the result:

Layout weight example

Leave a Comment