androidandroid-layoutandroid-layout-weightandroid-percent-layout

Set child to have a percentage width of a parent


There are 3 LinearLayout containers with horizontal orientation. The first two LinearLayout each have 4 TextView children. The third one has only 3. I have created and assigned style to all of the TextView children. Style fragment:

<item name="android:layout_width">0dp</item>
<item name="android:layout_weight">.25</item>

With this style first two rows are aligned nicely and each child TextView uses a quarter of parent's width. However TextView components in the third LinearLayout each use a third of parents width.

So components alignment is like this:

A1xxxx A2xxxx A3xxxx A4xxxx
B1xxxx B2xxxx B3xxxx B4xxxx
  C1xxxx  C2xxxx  C3xxxx

And not like this (as expected):

A1xxxx A2xxxx A3xxxx A4xxxx
B1xxxx B2xxxx B3xxxx B4xxxx
C1xxxx C2xxxx C3xxxx

Solution: I have tried manually changing android:layout_weight property for each child in the third row and if I set layout_weight of C1, C2 and C3 to 0.25 0.25 and 0.5 I get the desired alignment.

Question: I am doing something wrong since my initial solution to have each TextView have property <item name="android:layout_weight">.25</item> does not work as expected?


Solution

  • You are not doing anything wrong and the result that You are getting is expected.

    You just need to add android:weightSum to 1 to the third LinearLayout. Because, by default the value of android:weightSum is set to the sum of children's layout_weight