Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

自定義 Adapter 的 ListView 只顯示第一條數據:兇手是 ScrollView

自定義 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,或者直接使用可滾動的整體布局方案。

Copyright © Linux教程網 All Rights Reserved