zoukankan      html  css  js  c++  java
  • Android 动态获取ListView的高度

    今天介绍一下怎么动态的获取listview的高度。看代码:

     

    public static void setListViewHeightBasedOnChildren(ListView listView) {
            ListAdapter listAdapter = listView.getAdapter();
            if (listAdapter == null) {
                // pre-condition
                return;
            }
    
            int totalHeight = 0;
            for (int i = 0; i < listAdapter.getCount(); i++) {
                View listItem = listAdapter.getView(i, null, listView);
                // listItem.measure(0, 0);
                listItem.measure(
                        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                totalHeight += listItem.getMeasuredHeight();
            }
    
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = totalHeight
                    + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
            listView.setLayoutParams(params);
        }

    使用这个代码来获取listview的高度,需要注意一下几个问题:

    1、listview的item的根布局一定要是LinearLayout;

    2、调用这个方法需要在适配器数据加载更新之后;代码如下:

    mAdapter.notifyDataSetChanged();     Function.getTotalHeightofListView(mListView);

    3、获取item的高度也可以用注释掉的代码,效果一样的。

  • 相关阅读:
    线性筛2 筛约数个数
    背包板子
    线段树(指针板子)
    10.11 模拟赛(QBXT国庆Day3)
    10.6 体育成绩统计
    10.5 T3 DDP BZOJ 4712
    10.2模拟赛总结
    线性筛1
    CF165D Beard Graph
    2019 CSP-S第一轮(hsyz半日游)
  • 原文地址:https://www.cnblogs.com/phj981805903/p/3230040.html
Copyright © 2011-2022 走看看