Android:深度探究线性布局LinearLayout中权重(layout_weight)属性

来源:互联网 发布:java服务端开发技术 编辑:程序博客网 时间:2024/06/03 20:16

在LinearLayout布局中,子控件对于父布局的分割显得尤为重要,在不考虑适配的情况,我们可以设置具体的高度和长度来分配。但这样对于不同尺寸的设备要分别进行绘测,另一方面这样做代码的可复用性也是相当低的

所以,今天我们要介绍的是LiearLayout中的layout_weight属性,通过设置它可以按权重分割父布局(LinearLayout)

在讲解之前,提前说明一个使用规则,即在垂直排列的LinearLayout中,我们优先考虑子控件layout_height属性与layout_weight的搭配使用;反之,在水平排列的LinearLayout中,我们优先考虑子控件中layout_width与layout_weight的搭配。在下面的讲解中,统一将上面两种情况的layout_height与layout_width称为【排列方向属性】

1、排列方向属性为wrap_content

我们选用水平排列的LinearLayout进行本次演示,在布局中分别创建三个TextView。将它们的layout_width属性均设为“wrap_content”,分别将它们的layout_weight设置为1,2,3。相关布局代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/LinearLayout1"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal" >    <TextView        android:layout_weight="1"        android:layout_width="wrap_content"        android:layout_height="fill_parent"        android:text="ONE"        android:background="#00FFFF"        />    <TextView        android:layout_weight="2"        android:layout_width="wrap_content"        android:layout_height="fill_parent"        android:text="TWO"        android:background="#FFFF00"        />    <TextView        android:layout_weight="3"        android:layout_width="wrap_content"        android:layout_height="fill_parent"        android:text="THREE"        android:background="#FF00FF"        /></LinearLayout>

这里写图片描述

经测绘,TextView1的宽度为0.74inches,TextView2的宽度为1.25inches,TextView3的宽度为1.84inches

仔细观察,这三个控件的宽度比并不是1:2:3

为什么呢?

因为在layout_weight生效前,要提前将子控件的layout_width属性计算进内,我们来验证一下:

ONE、TWO的长度是0.25inches、0.375inches

这样三个控件去除内容宽度的结果约为:0.49、1、1.47

比例除去测量精度之后大概为:1:2:3

所以,这验证了“在layout_weight生效前,要提前将子控件的layout_width属性计算进内”

2、排列方向属性为fill_parent

接下来,我们将TextView的layout_width属性改为“fill_parent”,看看效果:

这里写图片描述

为什么TextView3目标丢失?且TextView1和TextView2比例不协调?

别着急,聪明的你在看完上面一节的内容后一定会记住这句话
“在layout_weight生效前,要提前将子控件的layout_width属性计算进内”

计算步骤:

因为fill_parent代表子控件与父控件相应属性一致,所以在这里设父控件的宽度为x:

3个子控件各占1个x的宽度,剩余宽度为x - 3x = -2x
按照1:2:3进行分配:

第1个:x+(-2x*1/6)=(2/3)x
第2个:x+(-2x*2/6)=(1/3)x
第3个:x+(-2x*3/6)= 0

因此,以2:1的方式显示前两个子控件,隐藏第3个控件是正确且可解释的

完。

阅读全文
0 0
原创粉丝点击