Android 自定義ListView只顯示第一條資料的問題
阿新 • • 發佈:2019-02-04
最近,要在應用中做一個功能,查詢SQLite資料庫中的記錄,用列表進行展示。
關於選擇哪種佈局,因為考慮到介面上要增加一些篩選條件,介面會稍顯複雜,所以就沒有繼承ListFragment,而是繼承了Fragment,並且用了自定義的ListView:
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:id="@+id/fragmentContainer" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:dividerHeight="1px" android:divider="#B8B8B8" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:background="#B8B8B8" android:dividerHeight="1px" android:divider="#B8B8B8" > <TextView android:id="@+id/title_index" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="序號" android:gravity="center_horizontal" android:textSize="13sp" /> <!--表頭 。。。 。。。--> </LinearLayout> <!--ListView主體--> <ListView android:id="@+id/samplelist" android:layout_width="fill_parent" android:layout_height="fill_parent" android:dividerHeight="1px" android:divider="#B8B8B8" > </ListView> </LinearLayout> </ScrollView>
資料庫裡有30條記錄,但執行的時候發現介面上只顯示了1條,檢視輸出的話,發現其實30條記錄都查出來的,因此判斷問題出在UI層面:
整了半天沒整出來,不過,不經意間發現這是一個以前遇到並解決過的問題,原來這是因為ListView處在ScrollView裡面之後導致的問題,解決方法如下:
/** * 為了解決ListView在ScrollView中只能顯示一行資料的問題 * * @param listView */ public static void setListViewHeightBasedOnChildren(ListView listView) { // 獲取ListView對應的Adapter ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { return; } int totalHeight = 0; for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回資料項的數目 View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); // 計運算元項View 的寬高 totalHeight += listItem.getMeasuredHeight(); // 統計所有子項的總高度 } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); // listView.getDividerHeight()獲取子項間分隔符佔用的高度 // params.height最後得到整個ListView完整顯示需要的高度 listView.setLayoutParams(params); }
然後在Activity或Fragment中呼叫該方法:
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { // Create an adapter to point at this cursor SampleCursorAdapter adapter = new SampleCursorAdapter(getActivity(), (SampleCursor)cursor); lv.setAdapter(adapter); Utils.setListViewHeightBasedOnChildren(lv); }
問題解決: