LayoutInflater类中的inflate方法是咱们经常使用的一个工具,无论是自定义view仍是ListView这类adapter类中,inflate方法都能帮助咱们生成咱们须要的view。那么inflate的原理是什么呢?下面就来分析下源码。java
inflate方法有几个重载的方法,可是最后都是调用到了其中的一个方法,也就是View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
,那么咱们就从这个方法开始往下看。node
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) { synchronized (mConstructorArgs) { Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate"); final Context inflaterContext = mContext; final AttributeSet attrs = Xml.asAttributeSet(parser); //1. 保留上一次的context对象 Context lastContext = (Context) mConstructorArgs[0]; //2.存储当前inflate的context对象 mConstructorArgs[0] = inflaterContext; View result = root; try { // Look for the root node. int type; //3.找到第一个START_TAG while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { // Empty } if (type != XmlPullParser.START_TAG) { throw new InflateException(parser.getPositionDescription() + ": No start tag found!"); } final String name = parser.getName(); ... //4.处理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 { // Temp is the root view that was found in the xml //5.建立xml中的view对象 final View temp = createViewFromTag(root, name, inflaterContext, attrs); ViewGroup.LayoutParams params = null; if (root != null) { if (DEBUG) { System.out.println("Creating params from root: " + root); } // Create layout params that match root, if supplied //6.获取root中默认的layoutParams params = root.generateLayoutParams(attrs); //7.若是不须要add到root中 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. //8.处理其余的子view 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) { //9.addview到rootview中去 root.addView(temp, params); } // Decide whether to return the root that was passed in or the // top view found in xml. 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; } }
在代码1处,用到了一个成员变量mConstructorArgs,这是一个大小为2的数组,用来存储view构造中须要用到两个对象:context和attributeSet.在代码3处,经过一个while循环处理,找到xml中的第一个start_tag,也就是咱们定义的root view。在代码4处,这里主要用来处理xml定义的<merge>
标签,这里不做赘述。在代码5处,经过createViewFromTag方法建立了view,也就是咱们刚刚处理的start_tag中的view,因此真正的建立是在这个方法中,咱们来看下这个方法。android
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs, boolean ignoreThemeAttr) { //1.处理view标签 if (name.equals("view")) { name = attrs.getAttributeValue(null, "class"); } // Apply a theme wrapper, if allowed and one is specified. //2.若是指定了Theme属性,用ContextThemeWrapper包装一下 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(); } //3.处理blink标签 if (name.equals(TAG_1995)) { // Let's party like it's 1995! return new BlinkLayout(context, attrs); } try { //4.mFactory,mFactory2提供了一种便捷操做让咱们能够本身定制view 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) { //5.若是没有指定上面的factory信息,那么久调用下面的机制建立view final Object lastContext = mConstructorArgs[0]; mConstructorArgs[0] = context; try { //6.系统view if (-1 == name.indexOf('.')) { view = onCreateView(parent, name, attrs); } else { //7.自定义的view 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; } }
代码1处,用来处理咱们在xml中定义的<view class="">
标签,获取view的类名。在代码2处,若是xml中有定义theme,须要用定义的Theme来wrapper一下context,生成一个新的ContextThemeWrapper。代码3处用来处理<Blink>标签,它是一种闪烁的布局处理,不细究。在代码4处,有多个Factory,这个几个Factory的做用是LayoutInflater为咱们提供了一些工厂方法,让咱们本身去createView,默认都是没有这些Factory方法。从代码5处开始就是LayoutInflate的内部建立view的过程。首先保存一下context,而后判断咱们的view的name中是否有.,也就是判断是不是自定义的view仍是系统中的view,咱们只看系统view的建立方法,也就是从代码6处开始往下看,调用onCreateView方法.数组
protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException { return createView(name, "android.view.", attrs); } public final View createView(String name, String prefix, AttributeSet attrs) throws ClassNotFoundException, InflateException { //1.检查map缓存中是否有缓存的构造器 Constructor<? extends View> constructor = sConstructorMap.get(name); Class<? extends View> clazz = null; try { Trace.traceBegin(Trace.TRACE_TAG_VIEW, name); if (constructor == null) { // Class not found in the cache, see if it's real, and try to add it //2.获取name表示的Class对象 clazz = mContext.getClassLoader().loadClass( prefix != null ? (prefix + name) : name).asSubclass(View.class); //3.filter过滤class对象 if (mFilter != null && clazz != null) { boolean allowed = mFilter.onLoadClass(clazz); if (!allowed) { failNotAllowed(name, prefix, attrs); } } //4.获取构造器 constructor = clazz.getConstructor(mConstructorSignature); constructor.setAccessible(true); //5.缓存构造器 sConstructorMap.put(name, constructor); } else { // If we have a filter, apply it to cached constructor if (mFilter != null) { // Have we seen this name before? Boolean allowedState = mFilterMap.get(name); if (allowedState == null) { // New class -- remember whether it is allowed 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); } } } //6.args实参,第一个参数是context Object[] args = mConstructorArgs; args[1] = attrs; //7.反射获取view,调用的就是new View(Context,AttributeSet) 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; } catch (NoSuchMethodException e) { InflateException ie = new InflateException(attrs.getPositionDescription() + ": Error inflating class " + (prefix != null ? (prefix + name) : name)); ie.initCause(e); throw ie; } ... }
代码1处检查sConstructorMap中是否有当前view的缓存的构造器,第一次处理的时候都没有,往下继续看。代码2处,使用反射,直接获得了一个view的Class对象,而后使用mFilter检查这个class对象是不是咱们容许建立的Class对象,默认这个filter是不做过滤的。代码4处,经过这个class对象建立一个Constructor构造器对象,从mConstructorSignature这个对象上能够看出,使用的是public View(Context, AttributeSet)这个构造器。代码5处用来缓存这个构造器对象。代码6处用来传参,第一个参数是context已经在以前的方法中设置过,args[1]传递attributeSet对象。代码7处使用反射直接生成了View,这样最后就生成了咱们须要View对象了。缓存
回到inflate方法中,createViewFromTag已经建立了咱们指定的view,接着往下看。代码六、7中,若是提供了inflate方法中第二个参数ViewGroup的话,会获取这个ViewGroup中的layoutParams,而且将它设置给刚刚生成出来的View上。处理完这些以后也就是晶晶处理了最开始的rootView,其余的子节点的view尚未处理。因此在代码8处,就是处理接下来的子view。咱们大体看一下代码.app
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException { rInflate(parser, parent, parent.getContext(), attrs, finishInflate); } void rInflate(XmlPullParser parser, View parent, Context context, AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); int type; while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { if (type != XmlPullParser.START_TAG) { continue; } final String name = parser.getName(); if (TAG_REQUEST_FOCUS.equals(name)) { parseRequestFocus(parser, parent); } else if (TAG_TAG.equals(name)) { parseViewTag(parser, parent, attrs); } else if (TAG_INCLUDE.equals(name)) { if (parser.getDepth() == 0) { throw new InflateException("<include /> cannot be the root element"); } parseInclude(parser, context, parent, attrs); } else if (TAG_MERGE.equals(name)) { throw new InflateException("<merge /> must be the root element"); } else { final View view = createViewFromTag(parent, name, context, attrs); final ViewGroup viewGroup = (ViewGroup) parent; final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs); rInflateChildren(parser, view, attrs, true); viewGroup.addView(view, params); } } if (finishInflate) { parent.onFinishInflate(); } }
大体看一下,仍是同样的配方,使用createViewFromTag建立接下来的每一个子View,因此不细究了。ide
最后在inflate方法中还须要判断是否须要将当前建立的view 加到第二个参数提供的ViewGroup中,这个判断就是第三个参数提供的。大体的流程也就是这样吧~~工具