// 通过反射生成 View 的参数,分别是 Context 和 AttributeSet 类staticfinalClass<?>[]mConstructorSignature=newClass[]{Context.class,AttributeSet.class};publicfinalViewcreateView(Stringname,Stringprefix,AttributeSetattrs)throwsClassNotFoundException,InflateException{Constructor<?extendsView>constructor=sConstructorMap.get(name);Class<?extendsView>clazz=null;if(constructor==null){// 从缓存中得到 View 的构造器,没有则调用 getConstructorclazz=mContext.getClassLoader().loadClass(prefix!=null?(prefix+name):name).asSubclass(View.class);if(mFilter!=null&&clazz!=null){booleanallowed=mFilter.onLoadClass(clazz);if(!allowed){failNotAllowed(name,prefix,attrs);}}constructor=clazz.getConstructor(mConstructorSignature);constructor.setAccessible(true);sConstructorMap.put(name,constructor);}else{// If we have a filter, apply it to cached constructorif(mFilter!=null){// 过滤,是否允许生成该 View// Have we seen this name before?BooleanallowedState=mFilterMap.get(name);if(allowedState==null){// New class -- remember whether it is allowedclazz=mContext.getClassLoader().loadClass(prefix!=null?(prefix+name):name).asSubclass(View.class);booleanallowed=clazz!=null&&mFilter.onLoadClass(clazz);mFilterMap.put(name,allowed);if(!allowed){failNotAllowed(name,prefix,attrs);}}elseif(allowedState.equals(Boolean.FALSE)){failNotAllowed(name,prefix,attrs);// 不允许生成该 View}}}Object[]args=mConstructorArgs;args[1]=attrs;finalViewview=constructor.newInstance(args);// 通过反射生成 Viewreturnview;
voidrInflate(XmlPullParserparser,Viewparent,Contextcontext,AttributeSetattrs,booleanfinishInflate)throwsXmlPullParserException,IOException{finalintdepth=parser.getDepth();inttype;// 若 while 条件不成立,则加载结束了while(((type=parser.next())!=XmlPullParser.END_TAG||parser.getDepth()>depth)&&type!=XmlPullParser.END_DOCUMENT){if(type!=XmlPullParser.START_TAG){continue;}finalStringname=parser.getName();// 从 XmlPullParser 中得到 name 出来解析if(TAG_REQUEST_FOCUS.equals(name)){// name 各种情况下的解析parseRequestFocus(parser,parent);}elseif(TAG_TAG.equals(name)){parseViewTag(parser,parent,attrs);}elseif(TAG_INCLUDE.equals(name)){if(parser.getDepth()==0){thrownewInflateException("<include /> cannot be the root element");}parseInclude(parser,context,parent,attrs);}elseif(TAG_MERGE.equals(name)){thrownewInflateException("<merge /> must be the root element");}else{finalViewview=createViewFromTag(parent,name,context,attrs);finalViewGroupviewGroup=(ViewGroup)parent;finalViewGroup.LayoutParamsparams=viewGroup.generateLayoutParams(attrs);rInflateChildren(parser,view,attrs,true);// 继续遍历viewGroup.addView(view,params);// 顶层 View 添加 子 View}}if(finishInflate){// 遍历解析parent.onFinishInflate();}}