转载请标明出处:
http://blog.csdn.net/xuehuayous/article/details/50629618;
本文出自:【Kevin.zhou的博客】
XmlResourceParser parser = getResources().getLayout(R.layout.activity_main); int eventType = parser.next(); while(eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { Log.d("Test", "START_TAG:" + parser.getName()); } if (eventType == XmlPullParser.END_TAG) { Log.d("Test", "END_TAG:" + parser.getName()); } eventType = parser.next(); }布局如下:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" /> </RelativeLayout>
LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.main, null);
LayoutInflater inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.main, null);
LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.main, null);
public static LayoutInflater from(Context context) { LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (LayoutInflater == null) { throw new AssertionError("LayoutInflater not found."); } return LayoutInflater; }第三种,只能在Activity中使用,可以看到获取的LayoutInflater实际上是Window接口的实现PhoneWindow的一个成员变量。
public LayoutInflater getLayoutInflater() { return getWindow().getLayoutInflater(); }我们在PhoneWindow的构造函数中找到了LayoutInflater的初始化:
public PhoneWindow(Context context) { super(context); mLayoutInflater = LayoutInflater.from(context); }好嘛,那么这么一来这三种获取LayoutInflater对象的方式其实都是一样的。
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) { return inflate(resource, root, root != null); }
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(); } }在第8行,调用Resource的getLayout()方法,将传入的布局id转为XmlParse,可见这是一个XML的解析器,来看下是如何生成的:
public XmlResourceParser getLayout(@LayoutRes int id) throws NotFoundException { return loadXmlResourceParser(id, "layout"); }调用的是loadXmlResourceParse(id, "layout"):
XmlResourceParserloadXmlResourceParser(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); } ... ... } }在第9行有个重要的 loadXmlResceParser(),来看下是如何定义的:
XmlResourceParser loadXmlResourceParser(String file, int id,int assetCookie, String type) throws NotFoundException { if (id != 0) { try { // 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) { 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(); } } } catch (Exception e) { ... ... } } ... ... }在第16行就是最主要的 mAssets.openXmlBlockAsset(assetCookie, file); 继续跟进AssetManager.opopenXmlBlockAsset():
final XmlBlock openXmlBlockAsset(int cookie, String fileName) throws IOException { synchronized (this) { if (!mOpen) { throw new RuntimeException("Assetmanager has been closed"); } long xmlBlock = openXmlAssetNative(cookie, fileName); if (xmlBlock != 0) { XmlBlock res = new XmlBlock(this, xmlBlock); incRefsLocked(res.hashCode()); return res; } } throw new FileNotFoundException("Asset XML file: " + fileName); }在第6行我们看到了openXmlAssetNative(cookie, fileName);看到这个名字我们大致知道在往下跟进就是系统本地语言编写的,看下这个方法的声明:
private native final long openXmlAssetNative(int cookie, String fileName);在 frameworks\base\core\jni\android_util_AssetManager.cpp中有如下:
static jint android_content_AssetManager_openNonAssetNative(JNIEnv* env, jobject clazz, jint cookie, jstring fileName, jint mode) { AssetManager* am = assetManagerForJavaObject(env, clazz); if (am == NULL) { return 0; } ... ... const char* fileName8 = env->GetStringUTFChars(fileName, NULL); Asset* a = cookie ? am->openNonAsset((void*)cookie, fileName8, (Asset::AccessMode)mode) : am->openNonAsset(fileName8, (Asset::AccessMode)mode); ... ... env->ReleaseStringUTFChars(fileName, fileName8); return (jint)a; }
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(); } }
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); Context lastContext = (Context) mConstructorArgs[0]; mConstructorArgs[0] = inflaterContext; View result = root; try { // Look for the root node. int type; // 跳过 START_DOCUMENT 类型 while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { // Empty } // 如果开始不为 START_TAG 那么肯定xml有错误 if (type != XmlPullParser.START_TAG) { throw new InflateException(parser.getPositionDescription() + ": No start tag found!"); } final String name = parser.getName(); // 如果为 merge 则必须要添加到其他ViewGroup上,即传入的第二个参数不能为空 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"); } // 递归inflateView rInflate(parser, root, inflaterContext, attrs, false); } else { // Temp is the root view that was found in the xml // 创建xml的根节点View final View temp = createViewFromTag(root, name, inflaterContext, attrs); ViewGroup.LayoutParams params = null; if (root != null) { // 生成root View的LayoutParams params = root.generateLayoutParams(attrs); if (!attachToRoot) { // Set the layout params for temp if we are not // attaching. (If we are, we use addView, below) temp.setLayoutParams(params); } } // 递归inflate子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) { // root非空并且attachToRoot为真则将xml文件的root view加到参数提供的root里 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) { // 返回xml解析的root View 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; } }
方法名称
|
对应inflate(parser, root, attachRoot) | 说明 |
inflate(xmlId, null)
|
inflater(parser, null, false)
|
生成View并返回 |
inflate(xmlId, root)
|
inflater(parser, root, true)
|
生成View添加到root上并返回root |
inflate(xmlId, null, false) |
inflate(parser, root, false) |
生成View并返回 |
inflate(xmlId, null, true) |
inflate(parser, null, true) |
生成View并返回 |
inflate(xmlId, root, false) |
inflate(parser, root, false) |
生成View并返回 |
inflate(xmlId, root, true) |
inflater(parser, root, true) |
生成View添加到root上并返回root |
private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) { return createViewFromTag(parent, name, context, attrs, false); }这个方法只有一行,调用了五个参数的createViewFromTag,并在第五个参数传入false。
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs, boolean ignoreThemeAttr) { ... ... 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 (Exception e) { ... ... } }仔细分析一下,发现里边的mFactory2和mFactory都为null,那么程序最终其实执行了这个方法里边的这一段:
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; } }
protected View onCreateView(View parent, String name, AttributeSet attrs) throws ClassNotFoundException { return onCreateView(name, attrs); }只是重载了一个方法:
protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException { return createView(name, "android.view.", attrs); }
if (view == null) { final Object lastContext = mConstructorArgs[0]; mConstructorArgs[0] = context; try { if (-1 == name.indexOf('.')) { //view = onCreateView(parent, name, attrs); view = createView(name, "android.view.", attrs); } else { view = createView(name, null, attrs); } } finally { mConstructorArgs[0] = lastContext; } }根据name是否包含"."都是调用的createView方法,只不过是第二个参数一个为"android.view"另一个为null。下面分析下createView:
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; ... ... if (constructor == 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); ... ... constructor = clazz.getConstructor(mConstructorSignature); constructor.setAccessible(true); sConstructorMap.put(name, constructor); } else { // If we have a filter, apply it to cached constructor ... ... } Object[] args = mConstructorArgs; args[1] = attrs; 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; ... ... }删除一些我们不关心的代码,这里的思路还是比较清晰的,通过反射根据找到那么对应的那个类的字节码文件,然后找到它的构造方法,然后实例化该类,得到一个View。这里我们看到得到构造函数的时候:
constructor = clazz.getConstructor(mConstructorSignature);那这个 mConstructorSignature是什么呢?
static final Class<?>[] mConstructorSignature = new Class[] { Context.class, AttributeSet.class};
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException { rInflate(parser, parent, parent.getContext(), attrs, finishInflate); }这里直接调用了rInflate方法:
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(); } }