Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

layout_weight 是怎麼分配剩餘空間的

編輯:關於 Android 程式設計

效果

程式碼

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="3"
        android:background="#D200D2" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#6f00D2" />

</LinearLayout>

為什麼 height 要寫 0dp

這是使用 weight 時最關鍵的一點。在垂直 LinearLayout 中,weight 分配的是「父容器量完子 View 之後剩下的空間」。如果子 View 的 height 寫成 wrap_content 或 match_parent,它會先依自身內容或父容器佔掉空間,剩下能給 weight 分的就變少了,比例也就不準。

寫成 0dp 表示「我本身不佔空間,全部由 weight 決定」,這樣 3 : 1 才是精確的 3 : 1。上面的例子中,兩個 TextView 會分別佔據父容器高度的 75% 與 25%。

同理,水平方向的 LinearLayout 用 weight 時,應該把 layout_width 設為 0dp,而 height 依需求設定。

其他注意事項

  • weight 是比例而非絕對值。3 與 1 的比值,跟 30 與 10 的效果相同。
  • 可以搭配 margin,但 margin 會先被扣除,再對剩下的空間做分配。
  • 巢狀使用時要小心。多層 LinearLayout 各自分配 weight,容易出現高度超出螢幕的情況,必要時改用 ConstraintLayout 的百分比或 guideline 會更可控。
  • weightSum 可用來明確指定父容器的權重總和,預設是 auto(即所有子 View weight 相加)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved