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();
版权声明:本文为yeziliuyang原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。