Android编程中,ScrollView嵌套ListView时,会无法正确的计算ListView的大小。解决的办法有如下两种:
解决方案1:直接把包含ListView控件的ScrollView控件从布局文件中去除,留下ListView控件,这是最简单快捷的解决办法,如果一定要在ScrollView中包含ListView,则参考解决方案2:
去除Scroll之前的XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFFFFF" android:orientation="vertical" > <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" > <ListView android:id="@+id/test_listView" android:layout_width="match_parent" android:layout_height="match_parent" android:fadingEdge="vertical"/> </LinearLayout> </ScrollView> </LinearLayout>
去除ScrollView之后的XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFFFFF" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" > <ListView android:id="@+id/test_listView" android:layout_width="match_parent" android:layout_height="match_parent" android:fadingEdge="vertical" /> </LinearLayout> </LinearLayout>
解决方案2:通过代码,根据当前的ListView的列表子项计算列表的高度:
public class MainActivity extends Activity { private ListView listView; private String[] adapterData = new String[] { "标题1", "标题2", "标题3"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mainActivity); listView = (ListView) findViewById(R.id.test_listView); listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,adapterData)); fixListViewHeight(listView); } public void fixListViewHeight(ListView listView) { // 如果没有设置数据适配器,则ListView没有子项,返回。 ListAdapter listAdapter = listView.getAdapter(); int totalHeight = 0; if (listAdapter == null) { return; } for (int index = 0, len = listAdapter.getCount(); index < len; index++) { View listViewItem = listAdapter.getView(index , null, listView); // 计算子项View 的宽高 listViewItem.measure(0, 0); // 计算所有子项的高度和 totalHeight += listViewItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); // listView.getDividerHeight()获取子项间分隔符的高度 // params.height设置ListView完全显示需要的高度 params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); } }
原文链接: http://jingyan.baidu.com/article/afd8f4de4695af34e386e969.html