估计很多人都对layout_weight这个属性感到疑惑。
下面就通过几个例子来分析一下layout_weight这个属性。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<TextView
android:text="red"
android:background="#aa0000"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"/>
<TextView
android:text="green"
android:background="#00aa00"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="2"/>
<TextView
android:text="blue"
android:background="#0000aa"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="3"/>
</LinearLayout>
</LinearLayout>
看了这个布局文件,估计大家会以为红:绿:蓝=3:2:1
但结果却是:
红:绿=2:1,而且没有蓝色。
到底是怎么一回事呢?
其实是这样子的:
首先看,3个TextView的排列方式:是水平排列的。
因为是水平排列,所以看TextView的Layout_width.发现都是fill_parent。就是每一个TextView都是填充它的父控件。
所以剩余空间为1-3=-2,然后再根据Layout_weight来分配剩余控件。
所以红色分到的剩余空间为-2/6=-1/3 .加上它原本占的空间1,所有它占有的控件为父控件的2/3
绿色分到的剩余空间为-2/6*2=-2/3.加上它原本占的空间1,所有它占有的控件为父控件的1/3
而蓝色分到的剩余空间为-2/6*3=-1.加上它原本占的空间1,所有它占有的控件为父控件的0.
所以得知为什么 红:绿=2:1。
所以在使用layout_weight的属性时,不用死记书上写的属性值越小,占的比重越大。
而只需要知道,layout_weight是用来分配剩余空间的,然后每个分配到的剩余空间加上它本来占有的空间就是它实际占有的空间。