首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android LinearLayout 中 layout_weight 屬性的詳細用法與權重分配機制

     編輯:程式設計疑難解答

核心原理

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 不生效(內容優先佈局)。
  • 嵌套 LinearLayout 時,父佈局需 weightSum 且子佈局 layout_weight 配合 0dp。

常見坑

  1. 忘記設置 0dp → 子視圖按內容大小顯示,權重無效。
  2. 垂直佈局中未設置 layout_height=0dp。
  3. 過度嵌套導致渲染性能下降,建議改用 ConstraintLayout。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved