ScrollView和ListView冲突问题解决

       最近在开发一个应用时用到了ScrollView和ListView,想在ListView上再放一个小的标题栏分割,然后整体超出屏幕后又能滚动显示。但是,在跟踪过程中发现,我们自己设置了ListViewAdapter后,getView(int position, View convertView, ViewGroup parent)函数虽然一直在调用,position却一直是0。然后在显示界面只能看到一个Item。而eclipse会提示“The vertically scrolling ScrollView should not contain another vertically scrolling widget (ListView)”。

       刚开始想想既然两种View冲突,那我去掉ScrollView吧,但是效果出来自测后发现,当ListView超出屏幕范围,界面根本都不会滚动显示,看来这个问题绕不过去了。在网上搜了下,发现并验证以下方法解决了,据说最早是在stackoverflow上最早有人解决的,有兴趣的可以多去逛逛。

       好,春花,上代码~

1、新增文件ListViewRelayout.java。

public class ListViewRelayout {

	public void setListViewHeightBasedOnChildren(ListView listView) {
		// get the list view adapter, so this function must be invoked after set the adapter.
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		
		int totalHeight = 0;
		// get the ListView count
		int count = listAdapter.getCount();
		for (int i = 0; i < count; i++) {
			View listItem = listAdapter.getView(i, null, listView);
			// measure the child view
			listItem.measure(0, 0);
			// calculate the total height of items
			totalHeight += listItem.getMeasuredHeight();
		}
		
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		// get divider height for all items and add the total height
		params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
    }
}
2、在ListActivity.java

    mAppListView.setAdapter(mAppListAdapter);
    mRelayout.setListViewHeightBasedOnChildren(mAppListView);


如果你还增加了对ListView的动态改变,那么,还需要在notifyDataSetChanged后再调用一次,如:

    mEnableAppListAdapter.notifyDataSetChanged();
    mUtil.setListViewHeightBasedOnChildren(mEnableAppListView);


这样我们的ListView的LayoutParam就会重新被设置,从而界面刷新时能看到全部显示的ListView。

对notifyDataSetChanged()感兴趣的同学可参考本博客另一篇文章《如何动态刷新ListView的显示---notifyDataSetChanged》,敬请关注。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章