线形布局下的layout_weight(比重)属性

在布局文件中设置layout_weight(比重)属性时,以宽为例,假如 android:layout_width="wrap_content",或者 android:layout_width="0dp",此时,设置的layout_weight属性和数值成正比;假如 android:layout_width="match_parent",此时,设置的layout_weight属性和数值成反比

具体说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<LinearLayout
android:layout_marginTop="50dp"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:background="#00f"
android:layout_weight="1"
></LinearLayout>
<LinearLayout
android:layout_marginTop="50dp"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:background="#0f0"
android:layout_weight="2"
></LinearLayout>
</LinearLayout>

效果是这样的:
pic
android:layout_width="wrap_content"设置为android:layout_width="0dp"效果和上图相同。


但是,假如布局文件是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_marginTop="50dp"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#00f"
android:layout_weight="1"
></LinearLayout>
<LinearLayout
android:layout_marginTop="50dp"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#0f0"
android:layout_weight="2"
></LinearLayout>
</LinearLayout>

效果是:
weight1
这是为什么呢?下面具体说明:
首先要理解layout_weight属性的定义:按比例分摊剩余父布局。第一种情况下,宽度为 0dp,所以剩余空间就是一个父布局的宽度(下面简称父宽),蓝色占的比重是 1,绿色是 2,它们的宽度就是 1:2,很好理解;说说第二种情况:蓝色宽度是match_parent,也就是 1 个父宽,绿色宽度也是match_parent,也是 1 个父宽,蓝色和绿色加起来是 2 个父宽,那么,剩余父布局就是:1 父宽 - 2 父宽 = -1 父宽,它们俩要按比例分摊这 -1 父宽,蓝色是 -1 * 1/3 = -1/3 父宽,绿色是 -1 * 2/3 = -2/3 父宽,蓝色原来占 1 父宽,所以最终结果是:1 父宽 + (-1/3 父宽) = 2/3 父宽,绿色最终结果是:1 父宽 + (-2/3 父宽) = 1/3 父宽,2/3 :1/3 = 2:1,也就是第二幅图的效果了。