当前位置: 移动技术网 > IT编程>移动开发>Android > ScrollView与ListView合用(正确计算Listview的高度)的问题解决

ScrollView与ListView合用(正确计算Listview的高度)的问题解决

2019年07月24日  | 移动技术网IT编程  | 我要评论

哈尔滨旅行社报价,超级点卡屋,阿屁虎

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

复制代码 代码如下:

@override 
protected void onmeasure(int widthmeasurespec, int heightmeasurespec) { 
    int expandspec = measurespec.makemeasurespec(integer.max_value >> 2, 
            measurespec.at_most); 
    super.onmeasure(widthmeasurespec, expandspec); 

第二步:写个计算listview每个item的方法:

复制代码 代码如下:

public void setlistviewheightbasedonchildren(listview listview) {

  // 获取listview对应的adapter

  listadapter listadapter = listview.getadapter();

  if (listadapter == null) {

   return;

  }

  int totalheight = 0;

  for (int i = 0; i < listadapter.getcount(); i++) { // listadapter.getcount()返回数据项的数目

   view listitem = listadapter.getview(i, null, listview);

   listitem.measure(0, 0); // 计算子项view 的宽高

   totalheight += listitem.getmeasuredheight(); // 统计所有子项的总高度

  }

  viewgroup.layoutparams params = listview.getlayoutparams();

  params.height = totalheight
    + (listview.getdividerheight() * (listadapter.getcount() - 1));

  // listview.getdividerheight()获取子项间分隔符占用的高度

  // params.height最后得到整个listview完整显示需要的高度

  listview.setlayoutparams(params);

 }

第三步:listview添加适配器后设置高度即可:

复制代码 代码如下:

listview.setadapter(adapter); 
new listviewutil().setlistviewheightbasedonchildren(listview); 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网