LayoutInflater 的 inflate 方法引发的 RelativeLayout 测量方法异常

LayoutInflater inflate 最终都会执行三个参数的方法

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
        if (DEBUG) {
            Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
                    + Integer.toHexString(resource) + ")");
        }

        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

三个参数的含义想必大家都很熟悉了,平时我们大家在 Adapter 中 getView() 方法 用 LayoutInflater 的时候一般都是这么用:

view = LayoutInflater.from(mContext).inflate(R.layout.xxx, viewGroup, false);

前段时间碰到一个问题,在 adapter 外面通过 getView 方法来获取 view ,然后测量拿到的 view 时候发生了 crash,而且 crash 只发生在系统版本低于 5.0 的机器上

View item = adapter.getView(0, null, null);
item.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

接着顺藤摸瓜,查找到 item 根布局为 RelativeLayout 然后找到 onMeasure 方法,找到版本的一些区别,

在低版本上:

这里写图片描述

高版本上是:

这里写图片描述

发现问题出在 adapter.getView(0, null, null),由于我们传入的 ViewGroup root, 为 null,所以 inflate() 方法并没有生成对应的 LayoutParam ,然后低版本的源码也没有进行判空的处理,知道原因后,我们对代码做一下修改,修复了这个问题。添加代码如下:

View item = adapter.getView(0, null, null);
item.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
item.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int itemHeight = item.getMeasuredHeight();
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值