android性能优化--布局加载原理

1.背景:

了解布局加载原理有利于项目中的优化布局,同时更能学习到源码级别对于布局逻辑的原理。

setContentView -> LayoutInflater->inflate->getLayout->createViewFromTag->Factory->createView-反射

2.源码分析

2.1.Activity.class

首先我们从主界面activity入口开始。

setContentView(R.layout.activity_main);
public void setContentView(@LayoutRes int layoutResID) {
    this.getDelegate().setContentView(layoutResID);
}
 public abstract void setContentView(@LayoutRes int var1);

 public void setContentView(int resId) {
     this.ensureSubDecor();
     //获取根节点
     ViewGroup contentParent = (ViewGroup)this.mSubDecor.findViewById(16908290);
     contentParent.removeAllViews();
     //加载布局资源,同时传入父布局
     LayoutInflater.from(this.mContext).inflate(resId, contentParent);
     this.mOriginalWindowCallback.onContentChanged();
 }

2.2.LayoutInflater.java

接下来layout的加载核心对象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();
   //获取xml解析器,简单了解
    final XmlResourceParser parser = res.getLayout(resource);
    try {
    //加载xml布局,继续深入
        return inflate(parser, root, attachToRoot);
    } finally {
        parser.close();
    }
}


 /**
     * Inflate a new view hierarchy from the specified XML node. 
     * 从xml文件节点中加载一个新的view结构
     *  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.
     */
    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;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }
 
                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
                    //从xml加载一个临时布局,深入
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
...
                }

            } 
            return result;
        }
    }

留意createViewFromTag方法


    /**
     * Creates a view from a tag name using the supplied attribute set.
     * <p>
     * <strong>Note:</strong> Default visibility so the BridgeInflater can
     * override it.
     *
     * @param parent the parent view, used to inflate layout params
     * @param name the name of the XML tag used to define the view
     * @param context the inflation context for the view, typically the
     *                {@code parent} or base layout inflater context
     * @param attrs the attribute set for the XML tag used to define the view
     * @param ignoreThemeAttr {@code true} to ignore the {@code android:theme}
     *                        attribute (if set) for the view being inflated,
     *                        {@code false} otherwise
     */
    View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
        if (name.equals("view")) {
            name = attrs.getAttributeValue(null, "class");
        }
            View view;
            if (mFactory2 != null) {
            	//首先由mFactory2创建view,factory是提供给外部进行hook的一种形式。
                view = mFactory2.onCreateView(parent, name, context, attrs);
            } else if (mFactory != null) {
            	//由mFactory创建view
                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的方法
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }

            return view;
         
    }

createView是创建视图,企图通过LayoutInflater’s ClassLoader通过加载view名称来初始化一个View。

 /**
     * Low-level function for instantiating a view by name. This attempts to
     * instantiate a view class of the given <var>name</var> found in this
     * LayoutInflater's ClassLoader.
     *
     * <p>
     * There are two things that can happen in an error case: either the
     * exception describing the error will be thrown, or a null will be
     * returned. You must deal with both possibilities -- the former will happen
     * the first time createView() is called for a class of a particular name,
     * the latter every time there-after for that class name.
     *
     * @param name The full name of the class to be instantiated.
     * @param attrs The XML attributes supplied for this instance.
     *
     * @return View The newly instantiated view, or null.
     */
    public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
            //使用map保存对象的实例,
        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);
                    }
                }
                //通过构造器的签名获取class的构造对象
                constructor = clazz.getConstructor(mConstructorSignature);
                constructor.setAccessible(true);
                sConstructorMap.put(name, constructor);
            } else {
                // If we have a filter, apply it to cached constructor
                ...
            }

            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;

        } 
    }

3.LayoutInflater.Factory

Hook you can supply that is called when inflating from a LayoutInflater.You can use this to customize the tag names available in your XML layout files.
提供一个可以进行hook的方式,你可以使用tag名称来定制自己的xml文件布局。通过Factory提供了一种hook的方法,方便开发者拦截LayoutInflater创建View的过程.比如:记录view加载的时间。

 public interface Factory {
	 public View onCreateView(String name, Context context, AttributeSet attrs);
}
public interface Factory2 extends Factory {
  public View onCreateView(View parent, String name, Context context, AttributeSet attrs);
}

Activity中setFactory的兼容性问题
Android因为有很多版本问题,不断修复完善,所以有很多的控件有兼容类,LayoutInflater也不例外,它的是 LayoutInflaterCompat,所以尽量使用兼容类来处理。

LayoutInflaterCompat.setFactory(LayoutInflater.from(this), new LayoutInflaterFactory()
       {
           @Override
           public View onCreateView(View parent, String name, Context context, AttributeSet attrs)
           {
                //你可以在这里直接new自定义View

                //你可以在这里将系统类替换为自定义View

                //appcompat 创建view代码
               AppCompatDelegate delegate = getDelegate();
               View view = delegate.createView(parent, name, context, attrs);

               //替换字体示例
               if ( view!= null && (view instanceof TextView))
               {
                   ((TextView) view).setTypeface(typeface);
               }

               return view;
           }
       });

4.总结

布局加载的问题:
1.涉及io的操作,比如xml文件要通过xml解析器加载到内存里,那么我们优化io流也是一个方向。
2.可以看到真正加载xml的时候,涉及反射,反射本来性能就不高,所以此处也是一个方向要优化的。
解决方案:使用代码书写布局逻辑,但代码书写比较繁琐,可以使用一些第三方框架来完成。这样不涉及io的读写,及反射的问题。至于到底反射为什么加载慢,请查阅:https://juejin.im/post/6844903965725818887,欢迎交流!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值