我們經(jīng)常使用layout_weight設(shè)置LinearLayout子控件的高度和寬度的占比,那子控件的高度和寬度究竟是怎么計(jì)算的叔壤?
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp">
<TextView
android:background="#da5845"
android:layout_weight="3"
android:layout_width="0dp"
android:layout_height="match_parent"/>
<TextView
android:background="#4577dc"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent"/>
</LinearLayout>
效果圖如下:
紅色占2/5,藍(lán)色占3/5
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp">
<TextView
android:background="#da5845"
android:layout_weight="3"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:background="#4577dc"
android:layout_weight="2"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
紅色占2/5,藍(lán)色占3/5
OK,那layout_weight的真正含義是當(dāng)控件設(shè)置了此屬性佳恬,那么控件高度或者寬度為自身的高度或?qū)挾燃由鲜S嗫臻g的占比急灭。
以第二段代碼為例妓盲,假設(shè)屏幕的寬度為W,兩個(gè)子控件的寬度都是match_parent檐迟,那么剩余的空間為W - 2W = -W补胚,第一個(gè)子控件的寬度為W + (-W * 3 / 5 ) = W * 2 / 5;同理第二個(gè)子控件的寬度為W * 3 / 5追迟。
注意:layout_weight只有在LinearLayout子控件上才能生效