Android LayoutInflater.inflate源码分析
layoutinflater.inflate源码详解
layoutinflater的inflate方法相信大家都不陌生,在fragment的oncreateview中或者在baseadapter的getview方法中我们都会经常用这个方法来实例化出我们需要的view.
假设我们有一个需要实例化的布局文件menu_item.xml:
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <textview android:id="@+id/id_menu_title_tv" android:layout_width="match_parent" android:layout_height="300dp" android:gravity="center_vertical" android:textcolor="@android:color/black" android:textsize="16sp" android:text="@string/menu_item"/> </linearlayout>
我们想在baseadapter的getview()方法中对其进行实例化,其实例化的方法有三种,分别是:
2个参数的方法:
convertview = minflater.inflate(r.layout.menu_item, null);
3个参数的方法(attachtoroot=false):
convertview = minflater.inflate(r.layout.menu_item, parent, false);
3个参数的方法(attachtoroot=true):
convertview = minflater.inflate(r.layout.menu_item, parent, true);
究竟我们应该用哪个方法进行实例化view,这3个方法又有什么区别呢?如果有同学对三个方法的区别还不是特别清楚,那么就和我一起从源码的角度来分析一下这个问题吧.
源码
inflate
我们先来看一下两个参数的inflate方法,源码如下:
public view inflate(@layoutres int resource, @nullable viewgroup root) { return inflate(resource, root, root != null); }
从代码我们看出,其实两个参数的inflate方法根据父布局parent是否为null作为第三个参数来调用三个参数的inflate方法,三个参数的inflate方法源码如下:
public view inflate(@layoutres int resource, @nullable viewgroup root, boolean attachtoroot) { // 获取当前应用的资源集合 final resources res = getcontext().getresources(); // 获取指定资源的xml解析器 final xmlresourceparser parser = res.getlayout(resource); try { return inflate(parser, root, attachtoroot); } finally { // 返回view之前关闭parser资源 parser.close(); } }
这里需要解释一下,我们传入的资源布局id是无法直接实例化的,需要借助xmlresourceparser.
而xmlresourceparser是借助android的pull解析方法是解析布局文件的.继续跟踪inflate方法源码:
public view inflate(xmlpullparser parser, @nullable viewgroup root, boolean attachtoroot) { synchronized (mconstructorargs) { // 获取上下文对象,即layoutinflater.from传入的context. final context inflatercontext = mcontext; // 根据parser构建xmlpullattributes. final attributeset attrs = xml.asattributeset(parser); // 保存之前的context对象. context lastcontext = (context) mconstructorargs[0]; // 赋值为传入的context对象. mconstructorargs[0] = inflatercontext; // 注意,默认返回的是父布局root. view result = root; try { // 查找xml的开始标签. int type; while ((type = parser.next()) != xmlpullparser.start_tag && type != xmlpullparser.end_document) { // empty } // 如果没有找到有效的开始标签,则抛出inflateexception异常. if (type != xmlpullparser.start_tag) { throw new inflateexception(parser.getpositiondescription() + ": no start tag found!"); } // 获取控件名称. final string name = parser.getname(); // 特殊处理merge标签 if (tag_merge.equals(name)) { if (root == null || !attachtoroot) { throw new inflateexception("<merge /> can be used only with a valid " + "viewgroup root and attachtoroot=true"); } rinflate(parser, root, inflatercontext, attrs, false); } else { // 实例化我们传入的资源布局的view final view temp = createviewfromtag(root, name, inflatercontext, attrs); viewgroup.layoutparams params = null; // 如果传入的parent不为空. if (root != null) { if (debug) { system.out.println("creating params from root: " + root); } // 创建父类型的layoutparams参数. params = root.generatelayoutparams(attrs); if (!attachtoroot) { // 如果实例化的view不需要添加到父布局上,则直接将根据父布局生成的params参数设置 // 给它即可. temp.setlayoutparams(params); } } // 递归的创建当前布局的所有控件 rinflatechildren(parser, temp, attrs, true); // 如果传入的父布局不为null,且attachtoroot为true,则将实例化的view加入到父布局root中 if (root != null && attachtoroot) { root.addview(temp, params); } // 如果父布局为null或者attachtoroot为false,则将返回值设置成我们实例化的view if (root == null || !attachtoroot) { result = temp; } } } catch (xmlpullparserexception e) { inflateexception ex = new inflateexception(e.getmessage()); ex.initcause(e); throw ex; } catch (exception e) { inflateexception ex = new inflateexception( parser.getpositiondescription() + ": " + e.getmessage()); ex.initcause(e); throw ex; } finally { // don't retain static reference on context. mconstructorargs[0] = lastcontext; mconstructorargs[1] = null; } trace.traceend(trace.trace_tag_view); return result; } }
上述代码中的关键部分我已经加入了中文注释.从上述代码中我们还可以发现,我们传入的布局文件是通过createviewfromtag来实例化每一个子节点的.
createviewfromtag
函数源码如下:
/** * 方便调用5个参数的方法,ignorethemeattr的值为false. */ private view createviewfromtag(view parent, string name, context context, attributeset attrs) { return createviewfromtag(parent, name, context, attrs, false); } view createviewfromtag(view parent, string name, context context, attributeset attrs, boolean ignorethemeattr) { if (name.equals("view")) { name = attrs.getattributevalue(null, "class"); } // apply a theme wrapper, if allowed and one is specified. if (!ignorethemeattr) { final typedarray ta = context.obtainstyledattributes(attrs, attrs_theme); final int themeresid = ta.getresourceid(0, 0); if (themeresid != 0) { context = new contextthemewrapper(context, themeresid); } ta.recycle(); } // 特殊处理“1995”这个标签(ps: 平时我们写xml布局文件时基本没有使用过). if (name.equals(tag_1995)) { // let's party like it's 1995! return new blinklayout(context, attrs); } try { view view; if (mfactory2 != null) { view = mfactory2.oncreateview(parent, name, context, attrs); } else if (mfactory != null) { view = mfactory.oncreateview(name, context, attrs); } else { view = null; } if (view == null && mprivatefactory != null) { view = mprivatefactory.oncreateview(parent, name, context, attrs); } if (view == null) { final object lastcontext = mconstructorargs[0]; mconstructorargs[0] = context; try { if (-1 == name.indexof('.')) { view = oncreateview(parent, name, attrs); } else { view = createview(name, null, attrs); } } finally { mconstructorargs[0] = lastcontext; } } return view; } catch (inflateexception e) { throw e; } catch (classnotfoundexception e) { final inflateexception ie = new inflateexception(attrs.getpositiondescription() + ": error inflating class " + name); ie.initcause(e); throw ie; } catch (exception e) { final inflateexception ie = new inflateexception(attrs.getpositiondescription() + ": error inflating class " + name); ie.initcause(e); throw ie; } }
在createviewfromtag方法中,最终是通过createview方法利用反射来实例化view控件的.
createview
public final view createview(string name, string prefix, attributeset attrs) throws classnotfoundexception, inflateexception { // 以view的name为key, 查询构造函数的缓存map中是否已经存在该view的构造函数. constructor<? extends view> constructor = sconstructormap.get(name); class<? extends view> clazz = null; try { // 构造函数在缓存中未命中 if (constructor == null) { // 通过类名去加载控件的字节码 clazz = mcontext.getclassloader().loadclass(prefix != null ? (prefix + name) : name).assubclass(view.class); // 如果有自定义的过滤器并且加载到字节码,则通过过滤器判断是否允许加载该view if (mfilter != null && clazz != null) { boolean allowed = mfilter.onloadclass(clazz); if (!allowed) { failnotallowed(name, prefix, attrs); } } // 得到构造函数 constructor = clazz.getconstructor(mconstructorsignature); constructor.setaccessible(true); // 缓存构造函数 sconstructormap.put(name, constructor); } else { if (mfilter != null) { // 过滤的map是否包含了此类名 boolean allowedstate = mfiltermap.get(name); if (allowedstate == null) { // 重新加载类的字节码 clazz = mcontext.getclassloader().loadclass(prefix != null ? (prefix + name) : name).assubclass(view.class); boolean allowed = clazz != null && mfilter.onloadclass(clazz); mfiltermap.put(name, allowed); if (!allowed) { failnotallowed(name, prefix, attrs); } } else if (allowedstate.equals(boolean.false)) { failnotallowed(name, prefix, attrs); } } } // 实例化类的参数数组(mconstructorargs[0]为context, [1]为view的属性) object[] args = mconstructorargs; args[1] = attrs; // 通过构造函数实例化view final view view = constructor.newinstance(args); if (view instanceof viewstub) { final viewstub viewstub = (viewstub) view; viewstub.setlayoutinflater(cloneincontext((context)args[0])) } return view; } catch (nosunchmethodexception e) { // ...... } catch (classnotfoundexception e) { // ...... } catch (exception e) { // ...... } finally { // ...... } }
总结
通过学习了inflate函数源码,我们再回过头去看baseadapter的那三种方法,我们可以得出的结论是:
第一种方法使用不够规范, 且会导致实例化view的layoutparams属性失效.(ps: 即layout_width和layout_height等参数失效, 因为源码中这种情况的layoutparams为null).
第二种是最正确,也是最标准的写法.
第三种由于attachtoroot为true,所以返回的view其实是父布局listview,这显然不是我们想要实例化的view.因此,第三种写法是错误的.
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!