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

Android GridView Item 等高佈局:使用 layout_weight 實現子項均分高度

     編輯:程式設計綜合問答

場景

GridView 每行一個 Item,Item 內部為垂直 LinearLayout 包含 9 個子 LinearLayout,要求 9 個子佈局等高、自適應屏幕高度。

解決方案:父容器垂直佈局 + 子項 weight=1

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

    <!-- 子項 1 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">
        <!-- 具體內容 -->
    </LinearLayout>

    <!-- 子項 2 ~ 9 同理,全部 weight="1" -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">
    </LinearLayout>
    <!-- ... 共 9 個 -->

</LinearLayout>

關鍵屬性組合

屬性值作用
layout_height0dp配合 weight 時必須為 0,避免自身高度干擾分配
layout_weight1所有子項權重相同,父容器剩餘高度均分
orientationvertical父容器垂直排列,子項依次佔據 1/9 高度

在 Adapter 中應用

  • Item 佈局 XML 即按上述結構編寫。
  • getView() 中直接 inflater.inflate(R.layout.item, parent, false),無需動態計算高度。
  • 不同屏幕高度下,系統自動按比例分配,保證 9 區等高。

避坑提醒

  • 若子項內部還有嵌套 LinearLayout,內層若也想均分,需繼續設 weight;否則用 wrap_content。
  • GridView 本身不控制 Item 高度,Item 根佈局 match_parent 由 GridView 行高決定;若需固定行高,可在 GridView 設置 android:rowHeight 或動態測量。
  • 過深嵌套影響渲染性能,考慮用 ConstraintLayout 扁平化。

「height=0dp + weight=1」是 Android 線性佈局等分空間的黃金法則,靈活應用於列表項、表單、儀表盤等場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved