Android: trying to understand android:layout_weight

99封情书 提交于 2019-11-27 10:55:49

问题


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

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

Case 2

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

Case 3

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

Case 4

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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3629331/android-trying-to-understand-androidlayout-weight

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!