GridView 每行一個 Item,Item 內部為垂直 LinearLayout 包含 9 個子 LinearLayout,要求 9 個子佈局等高、自適應屏幕高度。
<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_height | 0dp | 配合 weight 時必須為 0,避免自身高度干擾分配 |
layout_weight | 1 | 所有子項權重相同,父容器剩餘高度均分 |
orientation | vertical | 父容器垂直排列,子項依次佔據 1/9 高度 |
getView() 中直接 inflater.inflate(R.layout.item, parent, false),無需動態計算高度。LinearLayout,內層若也想均分,需繼續設 weight;否則用 wrap_content。GridView 本身不控制 Item 高度,Item 根佈局 match_parent 由 GridView 行高決定;若需固定行高,可在 GridView 設置 android:rowHeight 或動態測量。ConstraintLayout 扁平化。「height=0dp + weight=1」是 Android 線性佈局等分空間的黃金法則,靈活應用於列表項、表單、儀表盤等場景。