androidxmlandroid-linearlayoutandroid-layout-weight

Child views not getting equal space with `layout_weight` attribute


I am trying to create the following XML layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:weightSum="2">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="Hello"
        android:layout_weight="1"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="1">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Hello"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Hello"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Hello"/>
    </LinearLayout>

</LinearLayout>

I am expecting the first TextView and the inner LinearLayout to take up equal amounts of space but that is not happening. Image.

Can someone please suggest any fixes?


Solution

  • Try this once-

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:weightSum="2"
        tools:context=".MainActivity">
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="Hello" />
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:weightSum="3">
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="Hello" />
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="Hello" />
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="Hello" />
        </LinearLayout>
    
    </LinearLayout>