深入解析Android中View创建的全过程
前言
吸进这几天在看view的尺寸是怎样计算出来的,于是看了整个view被初始化的过程,结合系统源码总结了一下分享出来,方便需要的朋友或者自己以后有需要的时候看看,下面话不多说了,来看看详细的介绍吧。
从布局文件到layoutparams
首先从activity的setcontentview(int)
方法开始,只要设置了r.layout的布局文件,那么界面上就会显示出来对应的内容。所以以这个方法为初发点,然后往后跟踪代码。
public void setcontentview(@layoutres int layoutresid) { getwindow().setcontentview(layoutresid); initwindowdecoractionbar(); }
通过以上代码发现调用了window类的setcontentview方法,那么这个window对象mwindow又是怎么初始化的?在activity中搜索发现是在activity的attach方法中初始化的,构造了一个phonewindow对象。
如下代码所示:
final void attach(context context, activitythread athread, instrumentation instr, ibinder token, int ident, application application, intent intent, activityinfo info, charsequence title, activity parent, string id, nonconfigurationinstances lastnonconfigurationinstances, configuration config, string referrer, ivoiceinteractor voiceinteractor) { attachbasecontext(context); mfragments.attachhost(null /*parent*/); mwindow = new phonewindow(this); // 这里创建了window对象 mwindow.setcallback(this); mwindow.setonwindowdismissedcallback(this); mwindow.getlayoutinflater().setprivatefactory(this); // ... 中间部分代码省略 mwindow.setwindowmanager( (windowmanager)context.getsystemservice(context.window_service), mtoken, mcomponent.flattentostring(), (info.flags & activityinfo.flag_hardware_accelerated) != 0); if (mparent != null) { mwindow.setcontainer(mparent.getwindow()); } mwindowmanager = mwindow.getwindowmanager(); mcurrentconfig = config; }
在phonewindow的setcontentview(int)
方法中,发现是调用了layoutinflater的inflate(int, view)
方法,对这个布局文件进行转换成view,并添加到后面view这个参数中。
@override public void setcontentview(int layoutresid) { // note: feature_content_transitions may be set in the process of installing the window // decor, when theme attributes and the like are crystalized. do not check the feature // before this happens. if (mcontentparent == null) { installdecor(); } else if (!hasfeature(feature_content_transitions)) { mcontentparent.removeallviews(); } if (hasfeature(feature_content_transitions)) { // ... } else { mlayoutinflater.inflate(layoutresid, mcontentparent); } // ... }
这里面顺带穿插说一下view的根节点是怎样初始化出来的。
这里有一个关键的地方是这个installdecor()
方法,在这个方法中通过调用generatedecor()
方法创建了这个mdecor的对象,通过调用generatelayout(decorview)
方法初始化出来了mcontentparent对象。其中,mdecor是phonewindow.decorview
的类实例,mcontentparent是展示所有内容的,是通过com.android.internal.r.id.contentid
来找到这个view。
具体代码如下所示:
protected viewgroup generatelayout(decorview decor) { // ... view in = mlayoutinflater.inflate(layoutresource, null); // layoutresource是根据对当前显示view的activity的theme属性值来决定由系统加载对应的布局文件 decor.addview(in, new viewgroup.layoutparams(match_parent, match_parent)); mcontentroot = (viewgroup) in; viewgroup contentparent = (viewgroup)findviewbyid(id_android_content); if (contentparent == null) { throw new runtimeexception("window couldn't find content container view"); } // ... return contentparent; }
那么在哪里面可以看到这个decorview呢?看下面图。
下面这张图是在debug模式下连接手机调试app,使用layout inspector工具查看得到的图:
phonewindow.decorview
其中从1位置可以看出,整个view的根节点的view是phonewindow.decorview
实例;从2位置和3位置的mid可以推断出来,上面的mcontentparent就是contentframelayout类的实例;位置4中的蓝色区域是mcontentparent所表示的位置和大小。
以上图是在as 2.2.3版本上使用android monitor tab页中的layout inspector工具(参考位置5)生成。
紧接着跟踪上面layoutinflater中的inflate()
方法中调用,发现最后调用到了inflate(@layoutres int resource, @nullable viewgroup root, boolean attachtoroot)
方法中,在这个方法中构造了xmlresourceparser对象,而这个parser对象构造代码如下所示:
xmlresourceparser loadxmlresourceparser(int id, string type) throws notfoundexception { synchronized (maccesslock) { typedvalue value = mtmpvalue; if (value == null) { mtmpvalue = value = new typedvalue(); } getvalue(id, value, true); if (value.type == typedvalue.type_string) { return loadxmlresourceparser(value.string.tostring(), id, value.assetcookie, type); } throw new notfoundexception( "resource id #0x" + integer.tohexstring(id) + " type #0x" + integer.tohexstring(value.type) + " is not valid"); } } xmlresourceparser loadxmlresourceparser(string file, int id, int assetcookie, string type) throws notfoundexception { if (id != 0) { // ... // these may be compiled... synchronized (mcachedxmlblockids) { // first see if this block is in our cache. final int num = mcachedxmlblockids.length; for (int i=0; i<num; i++) { if (mcachedxmlblockids[i] == id) { //system.out.println("**** reusing xml block! id=" // + id + ", index=" + i); return mcachedxmlblocks[i].newparser(); } } // not in the cache, create a new block and put it at // the next slot in the cache. xmlblock block = massets.openxmlblockasset( assetcookie, file); if (block != null) { int pos = mlastcachedxmlblockindex+1; if (pos >= num) pos = 0; mlastcachedxmlblockindex = pos; xmlblock oldblock = mcachedxmlblocks[pos]; if (oldblock != null) { oldblock.close(); } mcachedxmlblockids[pos] = id; mcachedxmlblocks[pos] = block; //system.out.println("**** caching new xml block! id=" // + id + ", index=" + pos); return block.newparser(); } } // ... } // ... }
其中getvalue()
方法调用到本地frameworks/base/core/jni/android_util_assetmanager.cpp文件中的static jint android_content_assetmanager_loadresourcevalue
函数,而在这个函数中java层的typevalue的类对象value对象属性通过jni形式被赋值。
在构建这个parser时,经历了很复杂的过程,从typevalue中的assetcookie属性,到xmlblock中的xmlblock属性,再到xmlblock.parser中的mparsestate属性,都是用来保存jni层的数据,因为最终操作这些资源数据是在native层,所以必不可少通过jni这种方式,在java层和native层周旋。这里没有深入到native层去分析资源是如何被加载解析的,后面有机会再说。
最后跟到了这个public view inflate(xmlpullparser parser, @nullable viewgroup root, boolean attachtoroot)
方法中,代码如下所示:
public view inflate(xmlpullparser parser, @nullable viewgroup root, boolean attachtoroot) { synchronized (mconstructorargs) { final context inflatercontext = mcontext; final attributeset attrs = xml.asattributeset(parser); context lastcontext = (context) mconstructorargs[0]; view result = root; // ... // temp is the root view that was found in the xml final view temp = createviewfromtag(root, name, inflatercontext, attrs); // 这里将布局文件中的名称反射成具体的view类对象 viewgroup.layoutparams params = null; if (root != null) { // create layout params that match root, if supplied params = root.generatelayoutparams(attrs); // 这里将尺寸转换成了layoutparams if (!attachtoroot) { // set the layout params for temp if we are not // attaching. (if we are, we use addview, below) temp.setlayoutparams(params); } } // inflate all children under temp against its context. rinflatechildren(parser, temp, attrs, true); // we are supposed to attach all the views we found (int temp) // to root. do that now. if (root != null && attachtoroot) { root.addview(temp, params); // 将布局文件中根的view添加到mcontentparent中 } // ... return result; }
接着看view的generatelayoutparams(attributeset)
方法,因为这里返回了params。查看代码最后发现layoutparams的width和height属性赋值的代码如下所示:
public layoutparams(context c, attributeset attrs) { typedarray a = c.obtainstyledattributes(attrs, r.styleable.viewgroup_layout); setbaseattributes(a, r.styleable.viewgroup_layout_layout_width, r.styleable.viewgroup_layout_layout_height); a.recycle(); } protected void setbaseattributes(typedarray a, int widthattr, int heightattr) { width = a.getlayoutdimension(widthattr, "layout_width"); height = a.getlayoutdimension(heightattr, "layout_height"); }
通过查看typedarray类中的getlayoutdimension()
方法发现,获取的值是通过index在mdata这个成员数组中获取的。这个mdata的值是在创建typedarray对象时被赋的值,具体参见typedarray的obtain方法。这个数组是在resources的obtainstyledattributes()
方法中通过调用assetmanager.applystyle()
方法被初始化值的。applystyle()
方法是一个native方法,对应frameworks/base/core/jni/android_util_assetmanager.cpp文件中的android_content_assetmanager_applystyle
函数。在这个函数中发现,传入的resrouces类中的mtheme成员以及xmlblock.parse
类的mparsestate成员都是一个c++对象的指针,在java类中以整型或长整型值保存。
至此,布局文件中的尺寸值已经被转换成了具体的int类型值。
从布局文件到view
从上面的public view inflate(xmlpullparser parser, @nullable viewgroup root, boolean attachtoroot)
方法中看到view是通过这行代码final view temp = createviewfromtag(root, name, inflatercontext, attrs);
创建出来的,而这个name就是xml文件在解析时遇到的标签名称,比如textview。此时的attrs也就是上面分析的xmlblock.parser
的对象。最后发现view是在createviewfromtag()
方法中创建的,代码如下所示:
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(); } // ... 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; // ... }
这里要注意一下,mconstructorargs的第一个值是一个context,而这个context有可能已经不是当前activity的context。
看到这里,下面这样的代码片段是不是很熟悉?
if (name.equals("view")) { name = attrs.getattributevalue(null, "class"); }
上面factory这个接口对象在layoutinflater类中就有三个属性,分别对应:factory、factory2、mprivatefactory。很明显,弄清了这三个对象,也就知道了view的初始化流程。下面代码是对这三个属性的值的输出:
public class mainactivity extends appcompatactivity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); layoutinflater inflater = getlayoutinflater(); layoutinflater inflater1 = layoutinflater.from(this); field f = null; try { f = layoutinflater.class.getdeclaredfield("mprivatefactory"); f.setaccessible(true); } catch (nosuchfieldexception e) { e.printstacktrace(); } log.d("may", "the same object: " + (inflater == inflater1)); log.d("may", "inflater factory: " + inflater.getfactory() + ", factory2: " + inflater.getfactory2()); log.d("may", "inflater1 factory: " + inflater1.getfactory() + ", factory2: " + inflater1.getfactory2()); if (f != null) { try { log.d("may", "inflater mprivatefactory: " + f.get(inflater)); log.d("may", "inflater1 mprivatefactory: " + f.get(inflater1)); } catch (illegalaccessexception e) { e.printstacktrace(); } } } }
输出的log如下所示:
// 当前activiy继承的是android.support.v7.app.appcompatactivity the same object: true inflater factory: android.support.v4.view.layoutinflatercompathc$factorywrapperhc{android.support.v7.app.appcompatdelegateimplv14@41fdf0b0}, factory2: android.support.v4.view.layoutinflatercompathc$factorywrapperhc{android.support.v7.app.appcompatdelegateimplv14@41fdf0b0} inflater1 factory: android.support.v4.view.layoutinflatercompathc$factorywrapperhc{android.support.v7.app.appcompatdelegateimplv14@41fdf0b0}, factory2: android.support.v4.view.layoutinflatercompathc$factorywrapperhc{android.support.v7.app.appcompatdelegateimplv14@41fdf0b0} inflater mprivatefactory: com.jacpy.sb.mainactivity@41fd9e70 inflater1 mprivatefactory: com.jacpy.sb.mainactivity@41fd9e70 // 当前activity继承的是android.app.activity the same object: true inflater factory: null, factory2: null inflater1 factory: null, factory2: null inflater mprivatefactory: com.jacpy.sb.mainactivity@41fd9a28 inflater1 mprivatefactory: com.jacpy.sb.mainactivity@41fd9a28
首先看到mprivatefactory是当前的activity实例,因为activity也实现的factory2接口。首先看layoutinflater的创建过程,如下图所示:
layoutinflater初始化流程
而生成的phonelayoutinflater对象是缓存在contextimpl类的属性system_service_map中,所以通过context.layout_inflater_servic去取,始终是同一个对象,当然仅限于当前context中。
mprivatefactory属性的赋值是在activity的attach()方法中,通过调用mwindow.getlayoutinflater().setprivatefactory(this);
,因此调用factory2的oncreateview()
方法时,实际是调用activity中的oncreateview()
方法。而activity中的oncreateview()
实际返回的是null,所以最后创建view的是if判断中的oncreateview(parent, name, attrs)
方法,最后view是在layoutinflater类中的public final view createview(string name, string prefix, attributeset attrs) throws classnotfoundexception, inflateexception
方法中创建:
public final view createview(string name, string prefix, attributeset attrs) throws classnotfoundexception, inflateexception { constructor<? extends view> constructor = sconstructormap.get(name); class<? extends view> clazz = null; // ... // class not found in the cache, see if it's real, and try to add it clazz = mcontext.getclassloader().loadclass( prefix != null ? (prefix + name) : name).assubclass(view.class); // prefix传的值是android.view. // ... constructor = clazz.getconstructor(mconstructorsignature); // class<?>[] mconstructorsignature = new class[] { context.class, attributeset.class}; constructor.setaccessible(true); sconstructormap.put(name, constructor); // ... object[] args = mconstructorargs; args[1] = attrs; // 这个值是xmlblock.parser对象 final view view = constructor.newinstance(args); if (view instanceof viewstub) { // use the same context when inflating viewstub later. final viewstub viewstub = (viewstub) view; viewstub.setlayoutinflater(cloneincontext((context) args[0])); } return view; }
这里有没有发现mconstructorsignature数组的长度决定了调用了view的哪个构造方法?
总结
好了,以上就是这篇文章的全部内容了,至此,view已经创建成功。希望本文的内容对各位android开发者们能带来一定的帮助,如果有疑问大家可以留言交流。