1. 要点:必须在LinearLayout的布局内使用才有效果
2. 计算公式:
控件宽度=控件原始宽度+权重比例xLinearLayout剩余宽度。
3. 实践:
<?xml version="1.0" encoding="utf-8"?>
<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="vertical"
tools:context="com.example.android_develop_advance.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="width_0dp_weight_1" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="width_0dp_weight_2" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="width_math_weight_1"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="width_math_weight_2"/>
</LinearLayout>
</LinearLayout>
5. 计算:
控件宽度=控件原始宽度+权重比例xLinearLayout剩余宽度。
第一部分控件原始宽度:0dp
剩余宽度:屏幕宽度
权重:1/3 和2/3
width_0dp_weight_1控件的宽度= 0 + 1/3 x 屏幕宽度 = 1/3屏幕宽度
width_0dp_weight_2控件的宽度= 0 + 2/3 x 屏幕宽度 = 2/3屏幕宽度
第二部分控件原始宽度:match_parment
剩余宽度:屏幕宽度- 两个控件宽度(即两个屏幕宽度) = -屏幕宽度
权重:1/3 和2/3
width_match_weight_1控件的宽度= 屏幕宽度 + 1/3 x(- 屏幕宽度) = 2/3屏幕宽
width_match_weight_2控件的宽度= 屏幕宽度 + 2/3 x (-屏幕宽度) = 1/3屏幕宽度