Android:尝试了解 android:layout_weight
我试图将一个页面分为三个部分。我想以百分比值的形式执行此操作,但是 Android 不支持。相反,我必须使用android:layout_weight
。但我很难理解它并正确理解它。特别是实际尺寸是如何计算的。有没有办法从 android:layout_weight
中获取百分比值(0..100%)?
我通过几个案例(见附图)来描述问题。彩色字段都是
和 android:layout_height="fill_parent"
,因为我希望在这些字段之间划分全屏。
案例 1
好的,简单。每个
获得 33%。
案例 2
Ups?!第一个(黄色)
完全消失了?为什么?
案例3
又困惑了。黄色的
又回来了。然而,前两个重量较重的
会变小吗?到底是怎么回事?
案例 4
我完全不知道这一切背后的数学原理是什么。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然。让它们相加为 100。
对于您的“百分比值”,您希望
LinearLayout
中各个项目的android:layout_height
为0px
。Sure. Make them add up to 100.
For your "percentage value", you want the
android:layout_height
of the individual items within theLinearLayout
to be0px
.当您对栏使用 android:layout_height="fill_parent" 时,您不会留下任何可用空间。 (因为它们正在填充父级。)因为所有 3 个都设置为填充,所以请求的高度实际上是父级高度的 3 倍,因此权重将应用于负的剩余空间。这解释了您所看到的奇怪行为,以及为什么将layout_height 设置为 0px 可以解决它。
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.