如下代码所示,会出现什么现象?
<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/3match_parent
second宽度就是0+(match_parent-(0+0))2/3=2/3match_parent
正确设置之后
<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就可以达到效果。
更多Android进阶指南 可以扫码 解锁 《Android十大板块文档》
![](https://img-blog.csdnimg.cn/img_convert/6f80abd32253950ffad36c8d5f2c886d.jpeg)
1.Android车载应用开发系统学习指南(附项目实战)
2.Android Framework学习指南,助力成为系统级开发高手
3.2023最新Android中高级面试题汇总+解析,告别零offer
4.企业级Android音视频开发学习路线+项目实战(附源码)
5.Android Jetpack从入门到精通,构建高质量UI界面
6.Flutter技术解析与实战,跨平台首要之选
7.Kotlin从入门到实战,全方面提升架构基础
8.高级Android插件化与组件化(含实战教程和源码)
9.Android 性能优化实战+360°全方面性能调优
10.Android零基础入门到精通,高手进阶之路
敲代码不易,关注一下吧。ღ( ´・ᴗ・` ) 🤔