weight属性可以理解为权重。
关于weight属性有一个计算公式,但是并不需要记住那个公式,所以我也没记住=。=
我们只需要记住标准用法就好啦
1、用weight设置宽:将控件的width设置为0dp
android:layout_width=”0dp”
android:layout_weight=”2”
2、用weight设置高:将控件的height设置为0dp
android:layout_height=”0dp”
android:layout_weight=”2”
示例:
设置button1宽占1/3,button2占2/3
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/button1"
android:layout_height="wrap_content"
<!-- 注意这两行 -->
android:layout_width="0dp"
android:layout_weight="2"
android:text="111111" />
<Button
android:id="@+id/button2"
<!-- 注意这两行 -->
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="222222" />
</LinearLayout>
效果图:
根据上例:
button1 weight=2
button2 weight=1
所以button1的占比为: 2/(1+2)=2/3;
示例2:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3"
android:text="111111" />
<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="2222222" />
</LinearLayout>
效果图:
根据上例:
button1 weight=3
button2 weight=1
所以button1的占比为: 3/(1+3)=3/4;