自定義 Adapter 之後,ListView 死活只顯示第一條數據,這個問題困了我一晚上。
看 logcat,getView 裡的 list 分明有多條記錄,可 position 恆為 0,運行結果也只有 list[0] 的內容。折騰到最後才發現,問題根本不在 Adapter,而在布局文件。
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- listview -->
<ListView android:id="@+id/listview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
android:background="@drawable/home_index_btn_d"
android:fadingEdge="none"
android:cacheColorHint="#00000000"
android:scrollbars="vertical" />
</ScrollView>
罪魁禍首就是外層的 ScrollView。ListView 本身已經具備滾動能力,把它塞進 ScrollView 之後,高度測量被攪亂,ListView 只分到了「一條」的空間,剩下的行自然不會被 layout 出來。把 ScrollView 去掉,一切回歸正常。
這條經驗的推廣意義是:AbsListView 系列(ListView、GridView 等)不要嵌套在 ScrollView 中。如果確實需要「列表 + 其他內容」一起滾動,正確做法是把頭部與尾部做成 ListView 的 headerView / footerView,或者直接使用可滾動的整體布局方案。
Android 自定義 ListView 仿 iOS「阻尼」回彈效果
Android 自訂 Menu:ActionProvider 搭配 PopupWindow
Android 自訂 ListView + Gallery 混合列表實作
用 shape 自定義 Android ListView 圓角,省圖片也省記憶體
在兩個 Activity 之間傳遞自訂物件:Serializable 與 Parcelable
為 ListView 設計多欄自訂版面:SimpleAdapter 與 SimpleCursorAdapter
Android ListView 資料綁定:SimpleAdapter 與 SimpleCursorAdapter 實戰對比