「性能优化2.0」布局加载原理

「性能优化1.0」启动分类及启动时间的测量
「性能优化1.1」计算方法的执行时间
「性能优化1.2」异步优化
「性能优化1.3」延迟加载方案
「性能优化2.0」布局加载原理

一、布局加载原理

这一小节我们从源码的角度来分析 View 是如何加载的。

我简单的绘了一张流程图,根据这张图配合接下来的源码开始我们的工作吧:

View 加载过程

废话不多说,直接从 setContentView 作为切入点,分析 Activity 的布局加载原理。

1.1、Activity

  • Activity#setContentView
//Activity.java
public void setContentView(@LayoutRes int layoutResID) {
    //①
    getWindow().setContentView(layoutResID);
    initWindowDecorActionBar();
}

在①处 getWindow() 实际返回的是 Window 的实现类PhoneWindow

  • PhoneWindow#setContentView
//PhoneWindow.java
@Override
public void setContentView(int layoutResID) {
    
    ...   
    if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
        final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                getContext());
        transitionTo(newScene);
    } else {
        //①
        mLayoutInflater.inflate(layoutResID, mContentParent);
    }
    ...
}

在①处将加载·layoutResID·功能交给了 LayoutInflater布局加载器。

1.1、LayoutInflater

代码跟进到LayoutInflater,在深入源码前,先来大体了解一下 LayoutInflater 的作用,这里拷贝了源码的注释,从注释来看,它负责将 xml 的资源文件加载为一个 View 这样的一个功能。

所以这个过程会涉及两个步骤:

  1. 通过 IO 读取 xml 文件。
  2. 通过反射来创建对应的 View。
/**
 * Instantiates a layout XML file into its corresponding {@link android.view.View}
 */
@SystemService(Context.LAYOUT_INFLATER_SERVICE)
public abstract class LayoutInflater {...}

下面继续跟进源码来分析 inflate 的内部实现:

  • LayoutInflater#inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
//LayoutInflater.java
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
    final Resources res = getContext().getResources();
    ...
    //①
    final XmlResourceParser parser = res.getLayout(resource);
    try {
        //②
        return inflate(parser, root, attachToRoot);
    } finally {
        parser.close();
    }
}

①通过res.getLayout得到一个 XmlResourceParser ,XmlResourceParser 是用于解析要加载的那个布局。②根据返回的 parser 创建对应的 View 对象。这两个步骤就是我们所说的 通过 IO 读取 xml 文件通过反射来创建对应的 View。

  • Resource#getLayout
//Resources.java
@NonNull
public XmlResourceParser getLayout(@LayoutRes int id) throws NotFoundException {
    //①
    return loadXmlResourceParser(id, "layout");
}


//Resources.java
/**
 * Loads an XML parser for the specified file. ②
 *
 * @param id the resource identifier for the file
 * @param type the type of resource (used for logging)
 * @return a parser for the specified XML file
 * @throws NotFoundException if the file could not be loaded
 */
@NonNull
XmlResourceParser loadXmlResourceParser(@AnyRes int id, @NonNull String type)
        throws NotFoundException {
    final TypedValue value = obtainTempTypedValue();
    try {
        final ResourcesImpl impl = mResourcesImpl;
        impl.getValue(id, value, true);
        if (value.type == TypedValue.TYPE_STRING) {
            return impl.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");
    } finally {
        releaseTempTypedValue(value);
    }
}

① 最终通过调用loadXmlResourceParser获取到 XmlResourceParser ,在②中的注释可以看到Loads an XML parser for the specified file.可以看到这一步是将指定的 XML 格式的资源文件从磁盘中加载并解析为XmlResourceParser,便于接下来的解析工作。

  • LayoutInflater#inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
//LayoutInflater.java
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
    final Resources res = getContext().getResources();
    ...
    //①
    final XmlResourceParser parser = res.getLayout(resource);
    try {
        //②
        return inflate(parser, root, attachToRoot);
    } finally {
        parser.close();
    }
}

我们再回过头看上面的①这步中得到一个 XmlResourceParser 对象了,也就是说已经通过 IO 从磁盘中加载到对应的布局文件,接下来就要解析这个 XML 的每一个节点来创建对应的 View ,接下来是执行②步骤创建对应的 View。下面来看另外一个 inflate 重载方法。

  • LayoutInflater#inflate
//LayoutInflater.java
/**
 * Inflate a new view hierarchy from the specified XML node. Throws
 * {@link InflateException} if there is an error.
 */
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
    synchronized (mConstructorArgs) {
        ...
        View result = root;
        try {

            ...
            final String name = parser.getName();

            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
                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
                    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 all children under temp against its context.
                rInflateChildren(parser, temp, attrs, true);
                if (DEBUG) {
                    System.out.println("-----> done inflating children");
                }
                // 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);
                }
                // 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) {
            ...
        }
        return result;
    }

我们剔除了一部分代码,代码定位①处,我们看到执行了 createViewFromTag 就返回了一个 View 对象,并在②处添加在根视图中root。接下来我们来跟进 createViewFromTag 方法,看看内部是如何实现 View 的创建的。

  • LayoutInflater#createViewFromTag
//LayoutInflater.java
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) {
            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 (InflateException e) {
        ...
    }
    
       
}

在①处会判断是否设置了 Factory2 ,如果设置了,那么会将 View 的创建过程交给 Factory2 这个工厂去做,同样道理,②处也做了同样的判断。当然如果都没有设置,那么创建 View 的过程将直接交给 LayoutInflater 去实现,也就是到③的位置 onCreateView 。

  • LayoutInflater#onCreateView
//LayoutInflater.java
public final View createView(String name, String prefix, AttributeSet attrs)
        throws ClassNotFoundException, InflateException {
    Constructor<? extends View> constructor = sConstructorMap.get(name);
    if (constructor != null && !verifyClassLoader(constructor)) {
        constructor = null;
        sConstructorMap.remove(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
            //①
            clazz = mContext.getClassLoader().loadClass(
                    prefix != null ? (prefix + name) : name).asSubclass(View.class);
            if (mFilter != null && clazz != null) {
                boolean allowed = 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 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);
                }
            }
        }
        Object lastContext = mConstructorArgs[0];
        if (mConstructorArgs[0] == null) {
            // Fill in the context if not already within inflation.
            mConstructorArgs[0] = mContext;
        }
        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]));
        }
        mConstructorArgs[0] = lastContext;
        return view;
    } catch (NoSuchMethodException e) {
        ...    
    }
}

通过①类加载器加载 View 对应的 Class 对象,然后在②中获取 Class 对应的 Constructor 对象,然后在③反射创建 View 对象。

至此,我们大致走完 View 的创建过程,在 View 的加载中主要是分为两个过程,第一通过 IO 从磁盘中加载资源文件并封装为 XmlPullParser 对象,第二通过 XML 解析器解析 XML 并通过反射创建 View 对象。

二、总结

我们从源码的角度分析了 View 的加载过程,并且在上面还一个点没有跟进,那就是 Factory2 和 Factory 是使用的。我会在接下来性能优化的博客中来通过 Factory2 来实战获取 View 加载的耗时时间。

这里有两个需要关注的性能相关的问题:

  • IO 读取
  • 反射创建 View。

记录于 2019年3月20日

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,425评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,058评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,186评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,848评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,249评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,554评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,830评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,536评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,239评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,505评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,004评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,346评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,999评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,060评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,821评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,574评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,480评论 2 267