在学习layout_weight属性的时候在网上找了几篇文章说的我都不怎么理解,最后通过自己写的Demo 测试总结了一下,具体看下面的规则。
场景1
<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"
>
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_weight="2"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Button2" />
</LinearLayout>
注意这里Button的layout_width设置为代码权重设置为2:1
我们看到的结果却是1:2
场景2
<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"
>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_weight="2"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Button2" />
</LinearLayout>
这里Button的layout_width设置为wrap_content 代码权重设置为2:1
结果是 2:1这才是我们要的结果
下面我们要分析一下上面场景1和场景2
规则:
LinarLayout中layout_weight属性首先按照控件声明的尺寸进行分配然后再将剩下的尺寸按照weight分配
假设屏幕的宽为L
情况1:android:layout_width="wrap_content"
计算过程:
第一次计算
button1 宽为0 button2 宽为0
第二次计算: 剩下空间宽为:L
button1 宽为L/3 button2 宽为L*2/3
那么最后的结果:
button1 宽为L/3 button2 宽为L*2/3 也就是我们看到1:2
情况2:android:layout_width="fill_parent|match_parent"
计算过程:
第一次计算
button1 宽为L button2 宽为L
第二次计算: 剩下空间宽为: -L
button1 宽为-L/3 button2 宽为-L*2/3
那么最后的结果:
button1 宽为L*2/3 button2 宽为L/3 也就是我们看到2:1
欢迎大家吐糟!!