首先,我们来看一个例子:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="100dp"
tools:context="com.example.administrator.drawabletest.MainActivity">
<TextView
android:layout_width="0dp"
android:layout_height="50dp"
android:text="11111111111111111"
android:layout_weight="1"
android:background="#00FF00"
android:gravity="center"/>
<TextView
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="2"
android:text="2"
android:gravity="center"
android:background="#D2691E"/>
<TextView
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="3"
android:text="3"
android:gravity="center"
android:background="#9370DB"/>
</LinearLayout>
在上面的 xml 中,LinearLayout 中的三个 TextView 的 layout_width 都是 “0dp”,layout_weight 分别是 “1”,“2”,“3”,运行之后,三个 TextView 测量到的宽度是如下效果:
很明显,三个 TextView 的宽度的比是 1:2:3,这种用法也是我们在界面布局的时候经常使用的一种方法。下面我们把layout_width 的值都修改为 “wrap_content” :
这时候会有什么变化呢?我们来看看运行的效果:
很明显,现在可不是 1:2:3 的,比例了,那么 layout_weight (权重),到底是怎么样的一种测量规则呢?
是这样的:在布局中使用了 layout_weight 的属性之后,View 的宽度 (高度) = layout_width (layout_height) + 布局剩余的宽(高)*layout_weight
我们再来修改一下上面的例子:
运行结果:
我们来分析下 这种情况下系统是如何计算三个 TextView 的高度的呢?(假如屏幕宽度是480dp)
布局剩余的宽度 = 480dp - 100dp - 50dp = 330dp
textView1 的宽度 = 100dp + 330dp * 1/6 = 155dp
textView2 的宽度 = 50dp + 330dp * 2/6 = 160dp
textView3 的宽度 = 330 * 3/6 = 165dp
另外:
1,细心的同学们可能注意到了,第一个例子中绿色的 TextView 好些偏下了写,这是为什么呢? 因为 LinearLayout 中子 View 会自动基于基线对齐的,可以通过 baselineAligned = “false” 来取消基线对齐。
2,为什么是 layout_width 而不是 width 呢, 为什么不是 layout_gravity 而是 gravity 呢? 以 layout_ 前缀开头的都是该 View 在布局中的属性,例如 layout_width 的含义就是 View 在布局中的宽度;而 gravity 则指的是 View 本身的属性,gravity = “center” 的含义就是 TextView 上的文字相对于它本省而言据中,所以不以 layout_为前缀的属性指的就是 View 自身的属性。
3,像LinearLayout这样的布局还有一个 weightSum 的属性,系统默认的 weightSum 的值是我们在布局中写的 layout_weight 的总和,例如上一个例子中,weightSum 的值就是 6。当然我们也可以在 mxl 中自行指定,例如:
运行效果:
这时候 TextView 的宽度就是屏幕宽度的一半。