以前我们写LinearLayout的控件的权重的时候(以水平方向来说),都会将子控件的的宽度改成0dp
,然后 android:layout_weight=”1”,来表示子控件平分剩余空间。但是,如果子控件的宽度不设置成0dp,那个会是什么情形呢?下面一起来看看他们的区别和算法:
- 将子控件的宽度设置成0dp
代码如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center"
tools:context="com.example.linearlayout.MainActivity" >
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button1"
/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Button2"
/>
</LinearLayout>
- 这个很好理解,Button1的宽度为:1/(1 + 2 ) = 1/3。Button2的宽度为:2/(1 + 2 ) = 2/3。但是当把这两个个Button的宽度由0dp改成match_parent的时候,效果还会如上图所示吗?让我们来做个实验,代码如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center"
tools:context="com.example.linearlayout.MainActivity" >
<Button
android:layout_width="martch_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button1"
/>
<Button
android:layout_width="martch_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Button2"
/>
</LinearLayout>
效果图如下所示:
怎么会和上图不一样呢???这正好是我们要讲的算法,我们都知道,权重的作用是按比例分配屏幕剩余宽度。
算法为:控件自身的宽度 + 按比例分配的屏幕剩余宽度
假设手机屏幕的宽度为W,那么每个Button的宽度也应该都是W,剩余宽度就等于 W - (W + W) = -W。
Button1的weight=1,剩余宽度占比为1/(1 + 2) = 1/3,所以,最终宽度为 W + (1/3) * (-W) = 2/3W,Button2的计算类似,最终宽度为W + (2/3) * (-W) = 1/3W。所以就能够很好的理解上面两种为什么会有不同的效果了。