Layout_weight属性只有在Linearlayout中才有效果。
该属性跟android:layout_width为wrap_content和match_parent有很大关系。
简单的说:
以如下布局为例:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:background="#ff0000"
android:layout_width="**"
android:layout_height="wrap_content"
android:text="1"
android:textColor="@android:color/white"
android:layout_weight="1"/>
<TextView
android:background="#cccccc"
android:layout_width="**"
android:layout_height="wrap_content"
android:text="2"
android:textColor="@android:color/black"
android:layout_weight="2" />
<TextView
android:background="#ddaacc"
android:layout_width="**"
android:layout_height="wrap_content"
android:text="3"
android:textColor="@android:color/black"
android:layout_weight="3" />
</LinearLayout>
若android:layout_width为wrap_content时,此时系统会给三个TextView 分配空间,此空间刚好包裹住各自的内容,然后系统会 根据所设置的layout_width数值,将剩余的空间按比例分配。
若android:layout_width为match_parent时,此时这样计算剩余空间:
剩余空间数=屏幕宽度-3x屏幕宽度=-2屏幕宽度
第一个textview所占空间:屏幕宽度+(1/6)x(-2屏幕宽度)=2/3个屏幕宽度。
第二个textview所占空间:屏幕宽度+(2/6)x(-2屏幕宽度)=1/3个屏幕宽度。
第三个textview所占空间:屏幕宽度+(3/6)x(-2屏幕宽度)=0个屏幕宽度