LinearLayout Weight Tutorial

In a LinearLayout, you can use the android:layout_weight attribute to specify the weight of child elements. This attribute takes a floating point number to determine the proportion of space each child element occupies in the parent layout.

For instance, if a LinearLayout contains two child elements, one with android:layout_weight=”1″ and the other with android:layout_weight=”2″, the first child element will occupy one-third of the total space while the second child element will take up two-thirds of the total space.

The code example is shown below:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

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

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="Item 2" />

</LinearLayout>

In the example above, the first TextView has a weight of 1, and the second TextView has a weight of 2. Therefore, the first TextView occupies 1/3 of the total space, while the second TextView occupies 2/3 of the total space.

bannerAds