溫馨提示×

LinearLayout的weight屬性如何分配空間

小樊
120
2024-10-10 13:00:51
欄目: 云計算

在LinearLayout中,weight屬性用于指定子視圖在LinearLayout中所占的權重。當LinearLayout的寬度固定時,weight屬性可以根據子視圖的權重來分配空間。具體分配方式如下:

  1. 首先,為LinearLayout設置一個固定的寬度(例如android:layout_width="match_parent")。
  2. 為每個子視圖設置weight屬性,值為正數。例如,假設我們有兩個子視圖,一個寬度為100dp,另一個寬度為200dp,我們希望它們分別占據33%和67%的空間,那么可以將它們的weight屬性設置為12。

示例代碼:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <View
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <View
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2" />

</LinearLayout>

在這個示例中,第一個子視圖的寬度為100dp(1 * weight),第二個子視圖的寬度為200dp(2 * weight)。由于LinearLayout的寬度固定為match_parent,所以子視圖會根據權重分配空間。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女