1. 程式人生 > >有關Android ListView根據項數的大小自動改變高度問題

有關Android ListView根據項數的大小自動改變高度問題

第一種:按照listview的項數確定高度

    ListAdapter listAdapter = listView.getAdapter();  
    if (listAdapter == null) { 
        return; 
    } 

    int totalHeight = 0; 
    for (int i = 0; i < listAdapter.getCount(); i++) { 
        View listItem = listAdapter.getView(i, null, listView); 
        listItem.measure(0, 0); 
        totalHeight += listItem.getMeasuredHeight(); 
    } 

    ViewGroup.LayoutParams params = listView.getLayoutParams(); 
    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() – 1)); 
    ((MarginLayoutParams)params).setMargins(10, 10, 10, 10);
    listView.setLayoutParams(params); 

還有子ListView的每個Item必須是LinearLayout,不能是其他的,因為其他的Layout(如RelativeLayout)沒有重寫onMeasure(),所以會在onMeasure()時丟擲異常。

第二種:直接使用當前介面尺寸,稍加調整

ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = getWindowManager().getDefaultDisplay().getHeight() – 30;
// Toast.makeText(this, params.height+"", 3000).show();
listView.setLayoutParams(params);

XML佈局寫法,請注意這裡需要一個內部LinerLayout

<ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fadingEdge = "none"
        android:background="#FFF4F4F4"
        xmlns:android="

http://schemas.android.com/apk/res/android"
        >
   <LinearLayout
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:background="#fff4f4f4"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <ListView
        android:id="@+id/moreItemsListView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:cacheColorHint="#FFF4F4F4"
        android:dividerHeight="0.0dip"
        android:fadingEdge="none"
        />
   </LinearLayout>
</ScrollView>