自定義 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>
ListView 父容器高度確定(match_parent 或固定 dp)。Adapter 是否正確 setAdapter() 且未被覆蓋。getCount() 確實返回 > 0。getView() 第一行加 Log.d 驗證是否進入。九成以上 getView 不執行是佈局高度問題。將 ListView 高度設為 match_parent 或在 ConstraintLayout/LinearLayout 中配合 weight 佔滿剩餘空間,即可恢復正常回收與繪製機制。