Android ListView高度自适应和ScrollView冲突解决

在ScrollView中嵌套使用ListView,ListView只会显示一行到两行的数据。起初我以为是样式的问题,一直在对XML文件的样式进行尝试性设置,但始终得不到想要的效果。后来在网上查了查,ScrollView和ListView两个View都有滚动的效果,在嵌套使用时起了冲突,一般不建议两者套用。

 

下面说说具体解决方案。方案的主要思路就是根据ListView子项重置其高度。

首先,ListView不能直接用,要自定义一个,然后重写onMeasure()方法:

 1 import android.content.Context;
 2 import android.util.AttributeSet;
 3 import android.widget.ListView;
 4 
 5 public class MyListView extends ListView {
 6 
 7     public MyListView(Context context) {
 8     super(context);
 9     }
10     
11     public MyListView(Context context, AttributeSet attrs) {
12     super(context, attrs);
13     }
14     
15     public MyListView(Context context, AttributeSet attrs, int defStyle) {
16     super(context, attrs, defStyle);
17     }
18     
19     @Override
20     public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
21         int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
22                 MeasureSpec.AT_MOST);
23         super.onMeasure(widthMeasureSpec, expandSpec);
24     }
25 
26 }

第二步:写个计算listView每个Item的方法:

 1 public void setListViewHeightBasedOnChildren(ListView listView) {
 2 
 3   // 获取ListView对应的Adapter
 4 
 5   ListAdapter listAdapter = listView.getAdapter();
 6 
 7   if (listAdapter == null) {
 8 
 9    return;
10 
11   }
12 
13   int totalHeight = 0;
14 
15   for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目
16 
17    View listItem = listAdapter.getView(i, null, listView);
18 
19    listItem.measure(0, 0); // 计算子项View 的宽高
20 
21    totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
22 
23   }
24 
25   ViewGroup.LayoutParams params = listView.getLayoutParams();
26 
27   params.height = totalHeight
28     + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
29 
30   // listView.getDividerHeight()获取子项间分隔符占用的高度
31 
32   // params.height最后得到整个ListView完整显示需要的高度
33 
34   listView.setLayoutParams(params);
35 
36  }

在设置LIstView的Adapter后调用此方法便可。

 

但是要注意的是,子ListView的每个Item必须是LinearLayout,不能是其他的,因为其他的Layout(如RelativeLayout)没有重写onMeasure(),所以会在onMeasure()时抛出异常。

 

1 listView.setAdapter(adapter);  
2 setListViewHeightBasedOnChildren(listView);  

 

谢谢作者:http://www.jb51.net/article/37202.htm,http://blog.csdn.net/wulianghuan/article/details/8627958

 

posted @ 2015-04-28 23:55  will_N  阅读(11583)  评论(2编辑  收藏  举报