情形一
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:orientation="horizontal" >
<Button
android:id="@+id/crime_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="好好学习,天天向上"
android:layout_weight="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click"
android:layout_weight="1" />
</LinearLayout>
情形二
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:orientation="horizontal" >
<Button
android:id="@+id/crime_date"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="好好学习,天天向上"
android:layout_weight="1" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="click"
android:layout_weight="1" />
</LinearLayout>
比较上面代码运行的结果,我们可以总结android:layout_weight属性的工作原理如下:
第一步,LinearLayout查看layout_width属性值(竖直方位查看layout_height属性)。情形一中两个Button组件的layout_width属性都设置为wrap_content,因此他们获得的空间大小仅够绘制自身。
第二步,LinearLayout依据layout_weight属性值进行额外的空间分配。情形一中,两个Button组件拥有相同的layout_weight属性值,因此他们均分了同样大小的额外空间。若第一个Button组件的layout_weight值设置为2,那么它将获得2/3的额外空间,而第二个Button组件将获得1/3的额外空间。情形二中两个Button组件的layout_width属性都设置为0dp,就避开了第一步,又两个Button组件拥有相同的layout_weight属性值,所以Button组件具有相同的宽度。