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

时间:2021-12-30 07:14:58 

首先,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); 

标签:ScrollView,ListView
0
投稿

猜你喜欢

  • C#中的事务用法实例分析

    2022-04-03 05:23:37
  • Spring AOP实现接口请求记录到数据库的示例代码

    2023-08-15 19:14:05
  • 解决IDEA service层跳转实现类的快捷图标消失问题

    2022-09-03 06:38:00
  • IntelliJ IDEA 好用插件之analyze inspect code详解

    2021-09-26 22:16:36
  • android: targetSdkVersion升级中Only fullscreen activities can request orientation问题的解决方法

    2023-07-26 13:56:08
  • 简单谈谈Struts动态表单(DynamicForm)

    2022-10-07 07:24:29
  • C#中static静态变量的用法实例

    2022-12-16 07:47:44
  • 关于MVC与SpringMVC的介绍、区别、执行流程

    2023-11-28 02:25:56
  • Android实现简单旋转动画

    2023-11-07 09:50:58
  • java中Object类4种方法详细介绍

    2023-11-03 16:06:12
  • Spring框架事务属性中事务隔离级别与传播行为全面讲解

    2022-08-11 17:24:31
  • 如何在Spring Boot应用中优雅的使用Date和LocalDateTime的教程详解

    2023-03-14 04:54:11
  • 详解spring boot实现多数据源代码实战

    2022-05-01 20:18:36
  • Mybatis一对多查询的两种姿势(值得收藏)

    2023-07-01 00:20:08
  • C#实现启用与禁用本地网络的方式小结【3种方式】

    2022-04-21 18:45:14
  • Mybatis中的高级映射一对一、一对多、多对多

    2022-05-11 05:22:39
  • Spring请求参数校验功能实例演示

    2023-04-26 02:05:53
  • C#在图片增加文字的实现代码

    2023-03-30 03:26:24
  • 完美解决idea创建文件时,文件不分级展示的情况

    2022-01-01 22:10:19
  • java 中模式匹配算法-KMP算法实例详解

    2022-01-30 09:08:08
  • asp之家 软件编程 m.aspxhome.com