19

I'm trying to divide a page in three parts. I'd like to do it in percentage values, however that is not supported by Android. Instead I have to use android:layout_weight. But I have a hard time understanding it and getting it right. Especially how the actual size gets calculated. Is there a way to get a percentage value (0..100%) out of android:layout_weight?

I went through a few cases (see attached screenshot) to describe the problems. The colored fields are all <LinearLayout> with android:layout_height="fill_parent", because I want the full screen to be divided between those.

Case 1

alt text

Okay, simple. Every <LinearLayout> gets 33%.

Case 2

alt text

Ups?! The first (yellow) <LinearLayout> disappears completely? Why?

Case 3

alt text

Confused again. The yellow <LinearLayout> is back. However, the two first <LinearLayout> with the heavier weight get smaller? What is going on?

Case 4

alt text

I have absolutely no idea what the maths behind all this is.

divibisan
  • 11,659
  • 11
  • 40
  • 58
znq
  • 44,613
  • 41
  • 116
  • 144

2 Answers2

25

Is there a way to get a percentage value (0..100%) out of android:layout_weight?

Sure. Make them add up to 100.

For your "percentage value", you want the android:layout_height of the individual items within the LinearLayout to be 0px.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 8
    Mark, you made my day. You can't believe how much time I already spent trying to figure the weird cases out. And a simple `android:layout_height="0px"` solves everything :-) – znq Sep 02 '10 at 17:13
  • 1
    Setting layout_width to "fill_parent" and layout_weight to a float value like "0.2", "0.75" also works, in this case the smaller the number the bigger part of the space the element will take. Could you please tell if this is an acceptable way of doing it? – Yar Jun 11 '11 at 13:34
8

When you use android:layout_height="fill_parent" for the bars, you are not leaving any available space. (Since they are filling the parent.) Because all 3 are set to fill, the requested height is actually 3x the parent height, so the weights are being applied to a negative remaining space. This explains the weird behavior you are seeing, and why setting layout_height to 0px solves it.

Sean Kleinjung
  • 3,115
  • 2
  • 21
  • 15