今天仔细看了一下layout_weight这个属性,发现它还真挺特别的,做以记录:
首先影响这个属性的因素主要和子控件的android:layout_width有关,也就是说当子控件的width是wrap_content时weight的值越大,这个子控件占的空间也就越大。
这时是成正比的关系 。
当子控件的android:layout_width是fill_parent时,就完全相反了,weight值越大,子控件占用的空间反而越小。
可以总结为 当填充属性是wrap_content时,随着layout_weight的变大,该控件的优先级越高,
当填充属性是fill_parent时,随着layout_wight的变大,该控件的优先级越低,两者正好相反
下面是布局
<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<TextView
android:text="red"
android:gravity="center_horizontal"
android:background="#aa0000"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"/>
<TextView
android:text="green"
android:gravity="center_horizontal"
android:background="#00aa00"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"/>
<TextView
android:text="blue"
android:gravity="center_horizontal"
android:background="#0000aa"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"/>
<TextView
android:text="yellow"
android:gravity="center_horizontal"
android:background="#aaaa00"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<TextView
android:text="row one"
android:textSize="15pt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<TextView
android:text="row two"
android:textSize="15pt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<TextView
android:text="row three"
android:textSize="15pt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<TextView
android:text="row four"
android:textSize="15pt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
效果如下四个颜色不一样大小是因为textview字数不同 把TextView中的属性android:layout_width值改为"fill_parent"就可以一样大小了。其他的效果自己试试就知道了。
LinearLayout之间的layout_weight设置带来的影响,将第一个LinearLayout的layout_weight设置为2之后 会发现它的布局变小了。也就是说weight越大占的比例反而越小。
也就是说LinearLayout之间的layout_weight是按照反比例分配空间的。