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

ListView 的 getView 遲遲不執行?先檢查佈局有沒有留位置給它

編輯:關於 Android 程式設計

遇到「資料明明有、Adapter 也設了,畫面卻一片空白」的狀況,別急著懷疑 Adapter 邏輯。最常见的原因其實很樸素:佈局檔裡根本沒把那個列表要顯示的空間留給它。

典型現場

看下面這段佈局:

<com.xxx.view.BaseListView
    android:id="@+id/list_find"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:cacheColorHint="@android:color/transparent"
    android:divider="@drawable/base_horizontal_line"
    android:dividerHeight="1dp"
    android:fadingEdgeLength="0dp"
    android:fastScrollEnabled="true"
    android:paddingBottom="10dp" />

<com.xxx.view.BaseListView
    android:id="@+id/list_article"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:cacheColorHint="@android:color/transparent"
    android:divider="@drawable/base_horizontal_line"
    android:dividerHeight="1dp"
    android:fadingEdgeLength="0dp"
    android:fastScrollEnabled="true"
    android:paddingBottom="10dp" />

問題一目了然:id 為 list_find 的 View 高度是 match_parent,在垂直 LinearLayout 中已經把父容器的高度全部佔滿,緊接其後的 list_article 分不到任何剩餘空間,實際高度被壓成 0。控制項沒有可見區域,自然不會去執行 getView,資料也就顯示不出來。

常見的修正方式有幾種:把兩個列表的 layout_height 改為 0dp 並搭配 layout_weight 按比例分配;或者讓外層改為滾動容器、內部列表使用 wrap_content;若兩個列表是互斥顯示的,則透過 View.GONE/VISIBLE 切換,一次只留一個佔滿螢幕。

另外一個常見原因:getCount 為 0

ListView 的填充流程是先問 Adapter 要數量,數量為 0 就直接跳過所有 getView 呼叫。所以資料來源為 null、集合沒清乾淨、查詢條件寫錯導致回傳空清單,都會表現為「getView 完全沒被呼叫」。

排查順序建議

  • 在 getCount 上打中斷點,確認回傳值是否真的大於 0。
  • 確認 setAdapter() 確實有被執行,且是在 setContentView 之後。
  • 用 Layout Inspector 或开发者工具查看該控制項在畫面上的實際尺寸,高度為 0 就是被擠掉了。
  • 檢查上層是否處於 View.GONE,或父容器(例如某些 ScrollView 嵌套)限制了子 View 的測量方式。
  • 自定義 ListView 若重寫了 onMeasure 或 onLayout,也要確認沒有把子項的測量流程攔截掉。

一句話總結:getView 不被呼叫,九成不是 Adapter 的問題,而是控制項沒有拿到尺寸、或者資料源本身是空的。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved