ListView 的使用技巧-动态计算 ListView 的高度 – 热爱改变生活
我的GitHub GitHub |     登录
  • If you can't fly, then run; if you can't run, then walk; if you can't walk, then crawl
  • but whatever you do, you have to keep moving forward。
  • “你骗得了我有什么用,这是你自己的人生”
  • 曾有伤心之地,入梦如听 此歌

ListView 的使用技巧-动态计算 ListView 的高度

Android sinvader 5588℃ 0评论

今天遇到这样的一个问题,我在项目中要实现这样的一个效果,写了文本之后生成一条数据,然后放到 ListView 里面去显示,原来 ListView 因为数据是空是不显示的,然后他的高度也是 WrapContant,这样将数据源设置到 ListView 里面之后,虽然他的数据增多了,但是整个 ListView 显示的地方却还是那么大,比如有三条数据了,每条数据的 item 的的高度为 20dp,这样除去 divider 的高度之外,应该至少有 60dp 了。

但实际上,ListView 整体占用的高度只有不到 20dp,这 60dp 的内容就在这 20dp 的范围下面滚动,并不会根据 ListView 中 item 的高度以及个数来动态的调整整个 ListView 的高度,这时候,就需要我们根据整个 ListView 来计算它的高度了。

  1. public class ScrollAndListViewUtil {
  2. /**
  3. * 动态设置 ListView 的高度
  4. * @param listView
  5. */
  6. public static void setListViewHeightBasedOnChildren(ListView listView) {
  7. if(listView == null) return;
  8.  
  9. ListAdapter listAdapter = listView.getAdapter();
  10. if (listAdapter == null) {
  11. return;
  12. }
  13.  
  14. int totalHeight = 0;
  15. for (int i = 0; i < listAdapter.getCount(); i++) {
  16. View listItem = listAdapter.getView(i, null, listView);
  17. listItem.measure(0, 0);
  18. totalHeight += listItem.getMeasuredHeight();
  19. }
  20.  
  21. ViewGroup.LayoutParams params = listView.getLayoutParams();
  22. params.height = totalHeight + (1);
  23. // params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
  24. listView.setLayoutParams(params);
  25. }
  26. }

 

代码下载
¥ 有帮助么?打赏一下~

转载请注明:热爱改变生活.cn » ListView 的使用技巧-动态计算 ListView 的高度


本博客只要没有注明“转”,那么均为原创。 转载请注明链接:sumile.cn » ListView 的使用技巧-动态计算 ListView 的高度

喜欢 (0)
发表我的评论
取消评论
表情

如需邮件形式接收回复,请注册登录

Hi,你需要填写昵称和邮箱~

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址