Android xml中layout_weight属性的工作原理

来源:互联网 发布:java线程之间的通信 编辑:程序博客网 时间:2024/05/17 01:42

layout_weight属性用于告诉父布局如何安排子组件。

以水平的LinearLayout为例,它在分配子组件时使用的是layout_width和layout_weight参数的混合值。
现在假设LinearLayout对应的xml布局如下:

<LinearLayout    android:orientation="horizontal"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_marginLeft="@dimen/activity_horizontal_margin"    android:layout_marginRight="@dimen/activity_horizontal_margin">    <Button        android:id="@+id/crime_date"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_weight="1"/>    <CheckBox        android:id="@+id/crime_solved"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/crime_solved_label"        android:layout_weight="1"/></LinearLayout>

根据上面的布局,LinearLayout将如此安排布局:
第一步,LinearLayout查看layout_width属性值(竖直则看layout_height),布局情况如下:

由于上述的button和checkBox均是wrap_content,因此Button和Checkbox获得的空间仅够绘制自身。
如图可以看出,LinearLayout还会有一部分剩余空间。

第二步,LinearLayout按照layout_weight属性值进行剩余空间的分配,
由于上述代码中Button和Checkbox的weight值一致,于是二者将平分额外的空间。
此时布局如下:

layout_weight的值越大,组件获取剩余空间的比例越多。
例如假设Button的layout_weight为2,Checkbox的layout_weight的值仍为1,那么Button将获得剩余空间的2/3.

根据layout_weight的工作原理,我们可以看出:
如果试图让父布局完全按照layout_weight来分配子组件可用的空间,那么就要跳过上述第一步.
即设置layout_width或layout_height为0dp.

0 0
原创粉丝点击