ScrollView中嵌套ListView时显示不全的问题解决办法

最近在码代码的过程中将ScrollView内嵌套了ListView使用,结果出现一个问题,就是在ListView只显示了一两行,通过查阅资料发现是因为当ScrollView嵌套ListView时无法正确计算ListView的大小,在网上查阅资料后找到了几种解决办法,现总结如下:

1.在ScrollView中将android:fillViewport属性设置为"true",此方法适用于ScrollView中内容不是很多的情况,一般不使用;

2.当ListView处于ScrollView的最下部时,可以在代码中获取到ListView的属性,并将高度设置为Integer.MAX_VALUE;

3.当ListView不在ScrollView的最下部时,方法2不适用,此时需要在手动设置listview.setadapter()或者listview.notifyDataSetChangded后手动设置ListView的高度,代码如下:

private void setListViewHeightBasedOnChildren(ListView listView) {
		MyRecentWeatherAdapter<RecentWeather> adapter = (MyRecentWeatherAdapter<RecentWeather>) listView.getAdapter();
		if (adapter == null) {
			return;
		}
		int totalHeight = 0;
		Log.d("<<", "---->>itemcount " + adapter.getCount());
		
		for (int i = 0, len = adapter.getCount(); i < len; i++) {


<span style="white-space:pre">			</span>View listItem = adapter.getView(i, null, listView);


<span style="white-space:pre">			</span>// 计算子项View的宽高
<span style="white-space:pre">			</span>listItem.measure(0, 0);
<span style="white-space:pre">			</span>// 统计所有子项的总高度
<span style="white-space:pre">			</span>totalHeight += listItem.getMeasuredHeight();


<span style="white-space:pre">		</span>}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
		//listView.getDividerHeight()获取子项间分隔符占用的高度
		//params.height最后得到整个ListView完整显示需要的高度
		listView.setLayoutParams(params);
	}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值