ScrollView 中包含 ListView 的问题 : ScrollView和ListView会冲突,会导致ListView显示不全
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:fillViewport="true" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/id0" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/id1" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/id2" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/border" /> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> </ScrollView>
网上有人说需要设置ScrollView的一个属性
,但我去掉此设置之后依然是可正常显示的
另外ListView的Item的布局要是LinearLayout。(刚开始设置的是RelativeLayout,结果在动态设置高度时报空指针异常)
接着就在java文件中设置ListView的高度了
/*** * 动态设置listview的高度 * @param listView */ public void setListViewHeightBasedOnChildren(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); //在还没有构建View 之前无法取得View的度宽。在此之前我们必须选 measure 一下. totalHeight += listItem.getMeasuredHeight(); Log.i("xxxxxxxx listItem xxxxxxxxx", i + " height : " + totalHeight); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); // listView.getDividerHeight()获取子项间分隔符占用的高度 listView.setLayoutParams(params); }
在ListView的setAdapter(adapter)方法后调用上面的方法。
做完这些工作之后,就可在ScrollView中完整的显示ListView了。
当然,不推荐这种嵌套的方式,完全可以使用itenType来实现