解決ScrollView中ListView嵌套問題 和 listview顯示不全問題 。 查了好多大牛的解決方式,這種辦法比較好,親測可用。
注意setListViewHeightBaseOnChildren 放的位置,必須在listview.setAdapter()之後。
佈局文件代碼:
<ScrollView android:fillViewport="true" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:dividerHeight="0.0dp" android:layout_width="match_parent" android:layout_height="wrap_content"> </ListView> </ScrollView>java代碼類:
public class Utility { /** * 解決ScrollView中ListView嵌套問題 * @param listView */ public static void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { // pre-condition 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) + 95); //95爲: 解決listview顯示不全問題 listView.setLayoutParams(params); } }