首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >什么是android:weightSum在android中,它是如何工作的?

什么是android:weightSum在android中,它是如何工作的?
EN

Stack Overflow用户
提问于 2011-09-17 13:48:21
回答 5查看 180.9K关注 0票数 167

我想知道:什么是android:weightSum和布局权重,它们是如何工作的?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-09-17 13:59:26

根据文档,android:weightSum定义了最大权重和,如果未显式指定,则计算为所有子对象的layout_weight之和。

让我们考虑一个具有水平方向和3个ImageViewsLinearLayout的例子。现在,我们希望这些ImageViews始终占用相同的空间。为此,您可以将每个ImageViewlayout_weight设置为1,weightSum将被计算为等于3,如注释中所示。

代码语言:javascript
复制
<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对于为任何设备正确呈现布局非常有用,如果您直接设置宽度和高度,则不会出现这种情况。

票数 136
EN

Stack Overflow用户

发布于 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的空间会被布局占用,而其余的空间则是空的。

票数 179
EN

Stack Overflow用户

发布于 2013-04-16 19:49:24

如果未指定,则通过将所有子对象的layout_weight相加来计算总和。例如,可以通过将layout_weight设置为0.5并将weightSum设置为1.0,来为单个子进程提供总可用空间的50%。必须是浮点值,如"1.2“

代码语言:javascript
复制
    <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>
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7452741

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档