listvuew测量view高度时空指针问题

 private int getListViewHeightBasedOnChildren(Cart1Adapter listAdapter)
    {
        if (listAdapter == null)
        {
            return 0;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getGroupCount(); i++)
        {
            View groupItem = listAdapter.getGroupView(i, false, null, null);
            if (null != groupItem)
            {
                groupItem.measure(0, 0);
                totalHeight += groupItem.getMeasuredHeight();
                for (int j = 0; j < listAdapter.getChildrenCount(i); j++)
                {
                    View childItem = listAdapter.getChildView(i, j, false,
                            null, null);
                    if (null != childItem)
                    {
                        // 本身并无意义,但由于android的问题,不在measure之前设置一下宽高可能会导致空指针
                        RelativeLayout.LayoutParams ll = new RelativeLayout.LayoutParams(
                                LayoutParams.MATCH_PARENT,
                                LayoutParams.WRAP_CONTENT);
                        childItem.setLayoutParams(ll);
                        // childItem.measure(MeasureSpec.makeMeasureSpec(0,
                        // MeasureSpec.UNSPECIFIED), MeasureSpec
                        // .makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                        childItem.measure(MeasureSpec.makeMeasureSpec(
                                getResources().getDisplayMetrics().widthPixels,
                                MeasureSpec.EXACTLY), 0);
                        totalHeight += childItem.getMeasuredHeight();
                    }
                }
            }
        }
        return totalHeight;

    }

我们通常用这个方法来得到整个listview的高度,但是总是有很多空指针问题,在groupItem.measure(0, 0)这一句中,很容易就会报出一个空指针,这是后我们就要看看grouItem中inflate的布局了,如果引入的是LInearlayout是不会有任何问题的,但是如果是RelativeLayout,那么空指针就来了,所以在这个地方出现空指针时请去看看你的布局文件。或者我们可以像下面这样解决问题

RelativeLayout.LayoutParams ll = new RelativeLayout.LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        v.setLayoutParams(ll);

这个时候再去取v的高度是不会有问题的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值