I am trying to messing around with the Android layout weight attributes. I want a vertical layout with "3 child layouts" The first will take 25% of the space, the second 50%, and the last 25% of the space. When I try to add to the last layout, everything just not working. What should be the weight for each of these layouts?
I get the weight attributes to work fine with just 2 layouts/elements and understand how it works but when I try with 3 I get a problem.
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="100dp"
android:orientation="horizontal"
android:weightSum="100" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="100dp"
android:orientation="vertical"
android:layout_weight="25" >
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="100dp"
android:orientation="vertical"
android:layout_weight="50" >
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="100dp"
android:orientation="vertical"
android:layout_weight="25" >
</LinearLayout>
</LinearLayout>
Well, first, weight can only be applied to
LinearLayouts
or any layout that derives fromLinearLayout
. The weights of the children should be a percentage of whatever theweightSum
attribute is forLinearLayout
. If you setweightSum=1
of your parentLinearLayout
, then the percentage of your first child should be .25, second child should be .5, and third child should be .25.EDIT: Like javram said. You need to set either the width or height to
0dp
depending on whether theLinearLayout
is horizontal orientation or vertical orientation respectively.EDIT 2: Also, I don't think you have to actually specify
weightSum
. It helps, but I believeLinearLayout
will divide the children up base solely on how their own respective weights are. If child 1's weight is twice as large as child 2's weight, then child 2 will be double child 1 on screen. Thus in your case just make sure child 1 & 3 have the same weight while child 2 has double the value the other two.Make sure that the
android:width
attribute is set to 0dp for all child layouts, and then make sure that you have aweight
specified. If you want a more detailed explanation, you will need to paste your code.try using this code.
There is another way of achieving this result using less complicated layout tree. You may use
PercentRelativeLayout
from Percent Support Library for Android. Just import this library to your project, and check out the following code: