「性能优化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日

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值