layout_weight用于将所有子控件按weight的比例来分配布局,该属性只能用于TableLayout和LinearLayout。
比如我想把LinearLayout的几个子控件均分,那么可以设置每个子控件的layout_weight为1:
<LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="0dp" android:text="控件1" android:id="@+id/textView8" android:layout_weight="1" /> <TextView android:layout_width="wrap_content" android:layout_height="0dp" android:text="控件2" android:id="@+id/textView9" android:layout_weight="1" /> <TextView android:layout_width="wrap_content" android:layout_height="0dp" android:text="控件3" android:id="@+id/textView10" android:layout_weight="1" /> </LinearLayout>
子控件占用的大小为该控件的weight占所有子控件的比例。上面的例子3个控件的weight都为1,所以大小是均分的。
另外要注意,设置了weight后,把width或height设置为0dp。如果是水平布局设置width为0dp,垂直布局设置height为0dp。
不设置为0dp有什么问题?我试验过如果该控件内如果还嵌套子控件的话,会导致不能按所设置weight正确划分占用的空间。使用weight要注意该事项。