我想知道:什么是android:weightSum和布局权重,它们是如何工作的?
发布于 2011-09-17 13:59:26
根据文档,android:weightSum
定义了最大权重和,如果未显式指定,则计算为所有子对象的layout_weight
之和。
让我们考虑一个具有水平方向和3个ImageViews
的LinearLayout
的例子。现在,我们希望这些ImageViews
始终占用相同的空间。为此,您可以将每个ImageView
的layout_weight
设置为1,weightSum
将被计算为等于3,如注释中所示。
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
<!-- android:weightSum="3" -->
android:orientation="horizontal"
android:layout_gravity="center">
<ImageView
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="0dp"/>
.....
weightSum
对于为任何设备正确呈现布局非常有用,如果您直接设置宽度和高度,则不会出现这种情况。
发布于 2012-10-08 14:59:13
加上superM和Jeff的答案,
如果LinearLayout中有2个视图,第一个视图的layout_weight为1,第二个视图的layout_weight为2,并且未指定weightSum,则默认情况下,weightSum计算为3(子视图的权重之和),第一个视图占用1/3的空间,第二个视图占用2/3的空间。
但是,如果我们将weightSum指定为5,第一个将占用1/5的空间,而第二个将占用2/5的空间。因此,总共有3/5的空间会被布局占用,而其余的空间则是空的。
发布于 2013-04-16 19:49:24
如果未指定,则通过将所有子对象的layout_weight相加来计算总和。例如,可以通过将layout_weight设置为0.5并将weightSum设置为1.0,来为单个子进程提供总可用空间的50%。必须是浮点值,如"1.2“
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_rel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="2.0" >
<RelativeLayout
android:id="@+id/child_one"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:background="#0000FF" >
</RelativeLayout>
<RelativeLayout
android:id="@+id/child_two"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:background="#00FF00" >
</RelativeLayout>
</LinearLayout>
https://stackoverflow.com/questions/7452741
复制相似问题