Android LayoutInflater源码解析
2016-02-03 15:33
507 查看
转载请标明出处:
/article/7691973.html;
本文出自:【Kevin.zhou的博客】
前言:在《Android
setContentView源码解析》中解析中遇到我们设置的xml布局通过布局填充器LayoutInflater填充为View,并加载到mContentParent。关于LayoutInflater的原理没有涉及,那么这篇就主要去分析下LayoutInflater的源码。
Pull解析XML文件的方式与SAX解析XML文件的方式大致相同,他们都是基于事件驱动的。通过parser.next(),持续的解析XML文件直到文件的尾部。
下面我们来写一个简单的测试,把布局中的标签打印出来:
打印结果:
通过以上简单实例,我们对Pull解析器的解析方式有了大致了解。
第二种方法实质上和第一种是一个,LayoutInflater的from():
OK,到此我们搞清楚了是如何设置XmlParser的输入流xml布局文件的。
跑的有点远了,回到LayoutInflater的inflate()方法:
2. LayoutInflater.inflate(XmlPullParser parser,
对xml的DOM数进行解析为View结构,首先在第15行跳过开头的START_DOCUMENT,第21行做安全校验如果不为START_TAG则xml有错误,第29行开始处理<merge/>标签包括的布局,我们都知道<merge/>标签在UI结构优化中起到了非常重要的作用,使用它可以减少不必要的层级。如果为<merge/>标签则递归遍历DOM结构填充为View并添加到root
view。
如果不为<merge/>标签则通过createViewFromTag生成该DOM的根View,一个临时的root view,然后再递归遍历DOM结构填充为View并添加到root view。
这样就填充生成了View并返回给调用者。
通过以上分析,我们对LayoutInflater.inflate()带两个和三个参数进行简单的总结:
注:只要传递的root不为空,则会根据root来创建生成View的LayoutParams。
这么一来那我们关心的就是createViewFromTag、rInflateChildren以及rInflate,其实rInflateChildren就是调用的rInflate,下面我们把重点放在createViewFromTag及rInflate。
如果name包含"."那么说明这个View不是普通的,有可能是我们自己定义的控件。如果不包含"."那么说明是系统提供的控件,下面分别来分析下onCreateView和CreateView。
大爷个头,这里又调回到createView方法中了。
OK,这里其实就是反射获取的有两个参数的构造方法,这也就是为什么我们在做自定义控件的时候为什么要重载两个函数的构造函数的原因。
我们由 createViewFromTag 到 onCreateView 再到 createView 搞清楚了一件事情,那就是在inflate中如何生成的root view。生成root view之后就调用rInflateChildren(parser, temp, attrs, true);递归inflate子View。
在while循环中,我们抛开一些特殊标签直接看else里面的内容,这里先调用了一个createViewFromTag生成根view,然后 rInflateChildren → rInflate
→ rInflateChildren ... ... 就这样进入了循环一直到遍历完全,通过addView添加到父控件。
/article/7691973.html;
本文出自:【Kevin.zhou的博客】
前言:在《Android
setContentView源码解析》中解析中遇到我们设置的xml布局通过布局填充器LayoutInflater填充为View,并加载到mContentParent。关于LayoutInflater的原理没有涉及,那么这篇就主要去分析下LayoutInflater的源码。
一、 Pull解析器简单回顾
由于LayoutInflater在解析xml布局的时候使用的Pull解析器,作为知识储备我们先简单回顾下Pull解析器的使用。Pull解析XML文件的方式与SAX解析XML文件的方式大致相同,他们都是基于事件驱动的。通过parser.next(),持续的解析XML文件直到文件的尾部。
下面我们来写一个简单的测试,把布局中的标签打印出来:
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>
打印结果:
通过以上简单实例,我们对Pull解析器的解析方式有了大致了解。
二、 LayoutInflater的三种使用方式
在最初使用的时候感觉LayoutInflater是个很神奇的东西,可以将xml布局填充为View结构。一般使用的时候无外乎以下三种方式: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);
第二种方法实质上和第一种是一个,LayoutInflater的from():
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对象的方式其实都是一样的。
三、源码分析
1. LayoutInflater.inflate(int resource, ViewGroup root)
两个参数的的inflate会去调用三个参数的inflate,第三个参数即是否要把填充成的View添加到第二个参数传入的View。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; }
OK,到此我们搞清楚了是如何设置XmlParser的输入流xml布局文件的。
跑的有点远了,回到LayoutInflater的inflate()方法:
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(); } }
2. LayoutInflater.inflate(XmlPullParser parser,
ViewGroup root, boolean attachToRoot)
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; } }
对xml的DOM数进行解析为View结构,首先在第15行跳过开头的START_DOCUMENT,第21行做安全校验如果不为START_TAG则xml有错误,第29行开始处理<merge/>标签包括的布局,我们都知道<merge/>标签在UI结构优化中起到了非常重要的作用,使用它可以减少不必要的层级。如果为<merge/>标签则递归遍历DOM结构填充为View并添加到root
view。
如果不为<merge/>标签则通过createViewFromTag生成该DOM的根View,一个临时的root view,然后再递归遍历DOM结构填充为View并添加到root view。
这样就填充生成了View并返回给调用者。
通过以上分析,我们对LayoutInflater.inflate()带两个和三个参数进行简单的总结:
方法名称 | 对应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 |
这么一来那我们关心的就是createViewFromTag、rInflateChildren以及rInflate,其实rInflateChildren就是调用的rInflate,下面我们把重点放在createViewFromTag及rInflate。
3. LayoutInflater.createViewFromTag(View parent, String name, Context context, AttributeSet attrs)
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; } }
如果name包含"."那么说明这个View不是普通的,有可能是我们自己定义的控件。如果不包含"."那么说明是系统提供的控件,下面分别来分析下onCreateView和CreateView。
4. LayoutInflater.onCreateView(View parent, String name, AttributeSet attrs)
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); }
大爷个头,这里又调回到createView方法中了。
5. LayoutInflater.createView(String name, String prefix, AttributeSet attrs)
把createViewFromTag的核心拿过来,应该是这样的: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};
OK,这里其实就是反射获取的有两个参数的构造方法,这也就是为什么我们在做自定义控件的时候为什么要重载两个函数的构造函数的原因。
我们由 createViewFromTag 到 onCreateView 再到 createView 搞清楚了一件事情,那就是在inflate中如何生成的root view。生成root view之后就调用rInflateChildren(parser, temp, attrs, true);递归inflate子View。
5. LayoutInflater.rInflateChildren(parser, temp, attrs, true);
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(); } }
在while循环中,我们抛开一些特殊标签直接看else里面的内容,这里先调用了一个createViewFromTag生成根view,然后 rInflateChildren → rInflate
→ rInflateChildren ... ... 就这样进入了循环一直到遍历完全,通过addView添加到父控件。
结语
我们在接上篇《Android setContentView源码解析》之后,这篇主要分析了LayoutInflater布局填充器是如何将xml布局填充为View的。年前博客就写到这里吧,年后再写几篇关于View绘制的博客。祝各位朋友新年快乐!相关文章推荐
- 3D版的TagView,效果很赞
- Android抽象布局——include、merge 、ViewStub
- Android初学习 - visibility属性VISIBLE、INVISIBLE、GONE
- LeakCanary——直白的展现Android中的内存泄露
- Android TextView HTML链接
- Android Edittext监听
- Android 6.0: 动态权限管理的解决方案
- 2016年1月 Android 开发技巧总汇
- Bugly Android 快速接入使用文档
- Android 使用动态载入框架DL进行插件化开发
- Android View事件机制 21问21答
- Android进阶推荐书籍
- android使用MPAndroidChart开源图表折线图
- Android RecycleView(一)
- Android studio 下的robotium自动化测试和持续集成
- Android studio 下的robotium自动化测试和持续集成
- 如何学习 Android Animation?
- Android 6.0 Mtp(二) 应用层代码分析
- Android启动流程
- Android 内存泄漏总结