Android 性能优化之布局

1,046 阅读6分钟

Android 性能优化之布局(一)

前言

Android布局优化,是一个老生常谈的问题,以前都知道要减少布局的层级,可以UI优化,但是知其然不知其所以然,通过释然小师弟的LayoutInflater源码分析,我自己又去读了一遍源码,对于为什么这么做可以对性能有一个提升,在这里从setContentView开始,整理一下思路,做一个记录。

源码分析

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_layout)调用setContentView方法设置布局xml
    init()
    }
    接下来我们分析一下setContentView是怎么设置xml

AppCompatActivity.java

      /**
       * @return The {@link AppCompatDelegate} being used by this Activity.
       */

        @NonNull
        public AppCompatDelegate getDelegate() {
        if (mDelegate == null) {
        如果为空,创建一个AppCompatDelete
        mDelegate = AppCompatDelegate.create(this, this);
        }
        return mDelegate;
        
      继续向下追AppCompatDelegate是怎么创建的
     /**
      * Create an {@link androidx.appcompat.app.AppCompatDelegate} to use with {@code activity}.
      *
      * @param callback An optional callback for AppCompat specific events
      */
        @NonNull
        public static AppCompatDelegate create(@NonNull Activity activity,
           @Nullable AppCompatCallback callback) {
           这里return了一个Impl,继续追过去看
        return new AppCompatDelegateImpl(activity, callback);
        }
        
      在AppCompatDelegateImpl中我们会找到3个setContentView重载函数,这里只贴出其中一个方法,有需要的同学可自行查看源码

        @Override
        public void setContentView(int resId) {
        ensureSubDecor();
        ViewGroup contentParent = mSubDecor.findViewById(android.R.id.content);
        contentParent.removeAllViews();
        //调用LayoutInflater把布局放到contentParent里面
        LayoutInflater.from(mContext).inflate(resId, contentParent);
        mAppCompatWindowCallback.getWrapped().onContentChanged();
       }

到此发现setContentViwe是通LayoutInflater.from(mContext).inflate(resId, contentParent)将布局文件放到了contentParent中。需要进一步分析LayoutInflater的源码,看看是如何加载的xml,为什么布局的层级会影响性能。

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
    继续查看inflate做了些什么
    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) + ")");
    }
    此处调用XmlResourceParser这是一个xml解析接口以获取xml资源
    ,Android默认的xml解析器是XmlPullParser
    
    final XmlResourceParser parser = res.getLayout(resource);
    try {
    此处再次调用inflate的重载函数进行xml的解析
        return inflate(parser, root, attachToRoot);
    } finally {
        parser.close();
    }
}
//这里贴出inflate重载函数的官方注释
For performance reasons, view inflation relies heavily on pre-processing of
XML files that is done at build time. Therefore, it is not currently possible
to use LayoutInflater with an XmlPullParser over a plain XML file at runtime;
it only works with an XmlPullParser returned from a compiled resource

出于性能原因,视图的inflation是在构建的时候预编译解析的。因此,当前无法在运行时通过纯XML文件在XmlPullParser中使用LayoutInflater。
此处我的理解就是布局文件在编译的时候,提取被解析成xml,下面看源码中会发现,布局文件解析是通过反射创建View对象

由于代码过长,贴出部分关键代码
   public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
    synchronized (mConstructorArgs) {
        /**省略代码**/
        //定义返回值,初始化值为传入的root
        View result = root;

        try {
            // Look for the root node.
            int type;
            while ((type = parser.next()) != XmlPullParser.START_TAG &&
                    type != XmlPullParser.END_DOCUMENT) {
                // Empty
            }

            if (type != XmlPullParser.START_TAG) {
                throw new InflateException(parser.getPositionDescription()
                        + ": No start tag found!");
            }//对START_TAG,END_DOCUMENT,事件进行解析处理

            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");
                }
                //如果使用了merge标签,那么就在此进行递归处理。使用merge标签需注意,必须要有父布局并且要依赖父布局加载,不然会报异常
                rInflate(parser, root, inflaterContext, attrs, false);//此处圈起来
            } else {
                 //如果没有使用merge,那么创建一个临时的根视图temp
                // 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);//临时的params
                    }
                }
                  /**省略代码**/
                  //递归子布局
                   rInflateChildren(parser, temp, attrs, true);
                // Decide whether to return the root that was passed in or the
                // top view found in xml.
                if (root == null || !attachToRoot) {
                    result = temp;//将临时根视图赋值给开始定义的返回值result
                }
            }
           /**省略代码**/
        return result;
    }
}

final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
        boolean finishInflate) throws XmlPullParserException, IOException {
    rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}

到这里会发现不论哪种方式,最终都会调用rInflate()函数加载xml然后在这个函数中
又会调用一个很重要的函数createViewFromTag(),接下来分析一下这个函数

View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
        boolean ignoreThemeAttr) {
    if (name.equals("view")) {
        name = attrs.getAttributeValue(null, "class");
    }

    // Apply a theme wrapper, if allowed and one is specified.
    if (!ignoreThemeAttr) {
        final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
        final int themeResId = ta.getResourceId(0, 0);
        if (themeResId != 0) {
            context = new ContextThemeWrapper(context, themeResId);
        }
        ta.recycle();
    }
       if (name.equals(TAG_1995)) {
      // Let's party like it's 1995!
        return new BlinkLayout(context, attrs);
    }

        try {
        View view;
        //调用Factory来创建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('.')) {//含有"."tag的控件  比如一些自定义view
                    view = onCreateView(parent, name, attrs);
                } else {
                    view = createView(name, null, attrs);
                }
            } finally {
                mConstructorArgs[0] = lastContext;
            }
        }

        return view;
    } 
		/**省略代码**/
}
这里首先会用Factory.onCreateView获取一个View对象,如果获取不到,最终会调用createView()函数创建View对象

      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;
       //根据获取的构造器实例化一个View的对象
        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;
      }

总结

1.从第一步在onCreate中调用setContentViwe设置xml开始,一步一步查看源码,可以看到xml通过Layoutinflater解析实例化成一个View,是需要XmlPullParser解析xml,Java反射来操作创建View,这是一个很耗时的过程。如果布局层级过于复杂,那么递归调用所消耗的数据也就越长,执行反射的次数也会增加,就会带来性能上的问题。
2.使用merge标签可以减少布局的嵌套,减少了布局层级,那么创建view的时候可以让递归调用的时间缩短,反射的次数减少,从而达到一个性能的优化。
3.使用约束布局ConstraintLayout,可以有效减少布局时候的嵌套问题

当然,UI性能的优化不止于布局层级方面,View的过度绘制的优化,使用ViewStub进行懒加载,使用AsyncLayoutInflater异步加载布局等。Android10中新增了一个函数tryInflatePrecompiled,可以有效的解决布局方面优化的问题,这个函数我就在此不做赘述了,可以移步下方链接查看。

写在最后

感谢 「Android10源码分析」为什么复杂布局会产生卡顿?-- LayoutInflater详解 释然小师弟

本文未经允许禁止转载