前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >你真的了解android的layout_weight属性吗?

你真的了解android的layout_weight属性吗?

作者头像
砖业洋__
发布2023-05-06 17:08:19
1700
发布2023-05-06 17:08:19
举报
文章被收录于专栏:博客迁移同步

如下代码所示,会出现什么现象?

代码语言:javascript
复制
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#ff00ff"
            android:text="first" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:background="#ff0000"
            android:text="second" />
    </LinearLayout>

咦?怎么会出现这种情况?不是first占比是1/3吗?second占比是2/3吗?还有不是应该layout_width不是应该设置为0dp吗?

这现象怎么回事??

的确应该设置为0dp,下面就来解释一下为什么会出现这个奇怪的现象

被设置的weight值的控件,宽度应该为该控件的宽度+父控件的剩余空间*比例

水平方向的线性布局中:使用weight时,需注意将宽度设置为0dp

垂直方向的线性布局中:使用weight时,需注意将高度设置为0dp

这里以水平方向为例:

该控件所占的宽度=该控件原宽度+(父控件总宽度-已有控件总宽度)*比例

即 该控件原宽度+剩余宽度*比例

first的宽度:match_parent(原宽度) + (match_parent-(match_parent+match_parent)) * 1/3

如果不好理解,那么设match_parent为a

因为first和second空间的原有宽度都是match_parent,所以已有控件宽度是2a

first的宽度为:a+(a-2a)*1/3=2/3a

所以first的宽度为父控件的2/3,即占父控件的2/3

second的宽度为:a+(a-2a)*2/3=1/3a

所以second的宽度为父控件的1/3,即占父控件的1/3

要达到目的,就必须将layout_width应该设置为0dp,这样first宽度就是0+(match_parent-(0+0))*1/3=1/3*match_parent

second宽度就是0+(match_parent-(0+0))*2/3=2/3*match_parent

正确设置之后

代码语言:javascript
复制
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#ff00ff"
            android:text="first" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:background="#ff0000"
            android:text="second" />
    </LinearLayout>

垂直方向以此类推可得出结果。

这个“权重”属性仅仅在LinearLayout使用,在RelativeLayout没有这个属性。

容易出现的考题如下:

如这张图所示:

左边的代码会出现右上角的现象,文本的基线对齐导致出现了我们不想要的结果,那么就在LinearLayout中加上属性android:baselineAligned="false"

当只有一个TextView时,如何将其占据宽度的一半呢?

可以将其LinearLayout中添加android:weightSum=“2”,总权重为2,然后TextView的权重为1就可以达到效果。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-05-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档