ScrollView 与ListView共存会存在滚动的问题,并且ListView只显示一个半Item。 当ListView的高度设定一定的值时,ListView同样地会显示对应的高度的Item。 因此我们可以计算出这个ListView的总高度,再将它设置到ListView中,那么之前的滚动,高度问题也就不存在了。
补充一点: 当你的listView每个item是确定高度,就可以使用以下的方法. 但是假如你的item不是确定高度,是会变化的.当 你的Item 里面有个textView是包括宽度(就是用户输入过多的文字,导致换行.). 建议不要使用下面的方法.
totalHeight += listItem.getMeasuredHeight(); 这行代码,只会根据第一行出现的宽度计算下面的item,当其中有一个不同第一行的宽度,ScrollView 会不适应当前的高度.
代码片段(4)
[代码] 获取并设置ListView高度的方法
/** 自己补充的
最好在adapter.notifyDataSetChanged()之后再使用setListViewHeightBasedOnChildren,这个方法是计算你的listView的总高度,如果你的ListView没数据,在使用这个setListViewHeightBasedOnChildren,就会只有空LIstView的高度! 所以每次使用adapter.notifyDataSetChanged() 都使用setListViewHeightBasedOnChildren.
ScrollView 默认layoutHeight是wrap_content的 你也改不了,而且子节点只能有一个.
*/
| 01 | public void setListViewHeightBasedOnChildren(ListView listView) { |
| 02 | ListAdapter listAdapter = listView.getAdapter(); |
| 03 | if(listAdapter ==null) { |
| 08 | for(inti =0; i < listAdapter.getCount(); i++) { |
| 09 | View listItem = listAdapter.getView(i,null, listView); |
| 10 | listItem.measure(0,0); |
| 11 | totalHeight += listItem.getMeasuredHeight(); |
| 14 | ViewGroup.LayoutParams params = listView.getLayoutParams(); |
| 15 | params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() -1)); |
| 16 | ((MarginLayoutParams)params).setMargins(10,10,10,10); //设置maring .
|
| 17 | listView.setLayoutParams(params); |
[代码] XML布局
| 02 | android:layout_width="fill_parent" |
| 03 | android:layout_height="fill_parent" |
| 04 | android:fadingEdge ="none" |
| 05 | android:background="#FFF4F4F4" |
| 06 | xmlns:android="http://schemas.android.com/apk/res/android" |
| 09 | android:gravity="center_horizontal" |
| 10 | android:orientation="vertical" |
| 11 | android:background="#fff4f4f4" |
| 12 | android:layout_width="fill_parent" |
| 13 | android:layout_height="fill_parent" |
| 16 | android:id="@+id/moreItemsListView" |
| 17 | android:layout_width="fill_parent" |
| 18 | android:layout_height="fill_parent" |
| 19 | android:cacheColorHint="#FFF4F4F4" |
| 20 | android:dividerHeight="0.0dip" |
| 21 | android:fadingEdge="none" |
[文件] android_listView.rar ~ 911KB 下载(0)