android-layout-weight

Android LinearLayout given set of weights gives different column widths


Here is a LinearLayout with three columns with the centre column having half the weight of the other two -- the weights are 2, 1, 2, and the weightSum is 5.

I was expecting the centre column to be half as wide as the other two, but not so. Why?

enter image description here


<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:fitsSystemWindows="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <LinearLayout
        android:layout_marginTop="24dp"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="72dp"
        android:weightSum="5">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:background="#555"
            android:textSize="36dp"
            android:margin="6dp"
            android:text="left"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#555"
            android:textSize="36dp"
            android:margin="6dp"
            android:text="center"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:background="#555"
            android:textSize="36dp"
            android:margin="6dp"
            android:text="right"/>

    </LinearLayout>
    </LinearLayout>

Even more bizarrely, I have another example where the weights are also 2, 1, 2 and the centre column is wider than the outer ones. This makes no sense; what on Earth is going on?


Solution

  • Set the layout width of the textviews from "wrap_content" to "0dp" or if that failes to "match_parent"