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》,敬请关注。


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值