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

Android ListView 自定義 Adapter 時 getView 不執行?檢查佈局高度設定

     編輯:程式設計綜合問答

自定義 BaseAdapter 時,getCount() 回傳正確非零值,但 getView() 完全不被呼叫,Logcat 也無錯誤訊息。這通常是因為 ListView 的佈局高度設定錯誤,導致其測量高度為 0,系統認為無需繪製任何項目。

常見錯誤佈局

<!-- 錯誤:ListView 包裹在 wrap_content 的 ScrollView 中 -->
<ScrollView ...>
  <ListView
      android:layout_width="match_parent"
      android:layout_height="wrap_content" />  <!-- 關鍵錯誤 -->
</ScrollView>

ScrollView 會嘗試測量子 View 的完整高度,但 ListView 本身需要回收機制,wrap_content 會導致其無法正確計算高度,進而不繪製項目。

正確佈局寫法

<!-- 方案 1:直接讓 ListView 撐滿父容器 -->
<ListView
    android:id="@+id/myListView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<!-- 方案 2:若必須在 ScrollView 中,使用 NestedScrollView + 固定高度或 layout_weight -->
<androidx.core.widget.NestedScrollView ...>
  <ListView
      android:layout_width="match_parent"
      android:layout_height="0dp"
      android:layout_weight="1" />
</androidx.core.widget.NestedScrollView>

排查清單

  1. 確認 ListView 父容器高度確定(match_parent 或固定 dp)。
  2. 檢查 Adapter 是否正確 setAdapter() 且未被覆蓋。
  3. 確認 getCount() 確實返回 > 0。
  4. 在 getView() 第一行加 Log.d 驗證是否進入。

結語

九成以上 getView 不執行是佈局高度問題。將 ListView 高度設為 match_parent 或在 ConstraintLayout/LinearLayout 中配合 weight 佔滿剩餘空間,即可恢復正常回收與繪製機制。

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