layout_weight 指定子視圖在主軸方向上按權重分配剩余空間。前提:該方向 layout_width/height = 0dp(或 wrap_content 但權重生效需 0dp)。
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<View android:layout_width="0dp" android:layout_height="50dp"
android:layout_weight="1" android:background="#FF0000" />
<View android:layout_width="0dp" android:layout_height="50dp"
android:layout_weight="2" android:background="#00FF00" />
<View android:layout_width="0dp" android:layout_height="50dp"
android:layout_weight="1" android:background="#0000FF" />
</LinearLayout>
剩余寬度按 1:2:1 分配,紅:綠:藍 = 25%:50%:25%。
android:weightSum:指定總權重,默認所有子視圖 weight 之和。可用於預留空間(如 weightSum=4,三個子視圖 weight=1,剩余 25% 空白)。layout_width=0dp(水平)或 layout_height=0dp(垂直)必須設置,否則 weight 不生效(內容優先佈局)。weightSum 且子佈局 layout_weight 配合 0dp。layout_height=0dp。