Search code examples
androidandroid-layoutandroid-linearlayout

Auto space children of fixed-width LinearLayout


I have a row of text that I use a LinearLayout to represent:

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="A"
            tools:ignore="HardcodedText" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="B"
            tools:ignore="HardcodedText" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="C"
            tools:ignore="HardcodedText" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="D"
            tools:ignore="HardcodedText" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="E"
            tools:ignore="HardcodedText" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="F"
            tools:ignore="HardcodedText" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="G"
            tools:ignore="HardcodedText" />
    </LinearLayout>

I want these letters to be equally spaced in the LinearLayout (sort of like the auto margin in CSS); right now they just all sort of bunch together. How can I accomplish this?


Solution

  • This is easily accomplished by setting the layout_width of the LinearLayout to 0dp and the layout_weight of each TextView to 1.