美文网首页
Android源码之-深入理解LayoutInflater

Android源码之-深入理解LayoutInflater

作者: Android天之骄子 | 来源:发表于2017-12-18 21:46 被阅读0次

    前言

    LayoutInflater 在我们日常开发中扮演者重要的角色,但很多时候我们不知道它的重要性,因为它的重要性被隐藏在ActivityViewFragment等组件的光环之下。

    LayoutInflater类

    @SystemService(Context.LAYOUT_INFLATER_SERVICE)
    public abstract class LayoutInflater {
      ...
    }
    

    LayoutInflater 是一个抽象类,我们需要找到它的实现类。在上一篇Android源码中的单例模式 中我们知道上下文ContextImpl在加载时会通过SystemServiceRegistry 来注册服务,将LayoutInflaterServiceFetcher 注入到容器中,具体代码如下:

            registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
                    new CachedServiceFetcher<LayoutInflater>() {
                @Override
                public LayoutInflater createService(ContextImpl ctx) {
                    return new PhoneLayoutInflater(ctx.getOuterContext());
                }});
    

    这里创建的一个PhoneLayoutInflater 实例,PhoneLayoutInflater 就是继承自LayoutInflater

    public class PhoneLayoutInflater extends LayoutInflater {
        //内置View类型的前缀,如TextView的完整路径是android.widget.TextView
        private static final String[] sClassPrefixList = {
            "android.widget.",
            "android.webkit.",
            "android.app."
        };
        ...
        @Override 
        protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
            for (String prefix : sClassPrefixList) {
                try {
                    View view = createView(name, prefix, attrs);
                    if (view != null) {
                        return view;
                    }
                }
            }
            return super.onCreateView(name, attrs);
        }
    
        public LayoutInflater cloneInContext(Context newContext) {
            return new PhoneLayoutInflater(this, newContext);
        }
    }
    

    代码不多,核心代码就是重写了LayoutInflateronCreateView 方法,该方法的作用就是在传递进来的View 名字前面加上“android.widget.”或者“android.webkit.” 。最后,根据类的完整路径来构造对应的View 对象。

    LayoutInflater的inflate方法

    已经找到了LayoutInflater 的实现类,我们看下LayoutInflaterinflater 方法:

        //参数1 为xml解析器,参数2 要解析布局的root,参数3 是否要将解析的布局添加到父布局中
        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();
                   
                    //1.解析merge标签
                    if (TAG_MERGE.equals(name)) {
                        //只能使用有效的ViewGroup根目录和attachToRoot = true来使用<merge/>
                        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 {
                        //2. 这里是通过xml的tag来解析layout的视图 (详情看Pull解析)
                        //name就是要解析视图的类名 如RelateLayout
                        final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                        
                        ViewGroup.LayoutParams params = null;
    
                        if (root != null) {
                            // 生成布局参数
                            params = root.generateLayoutParams(attrs);
                            if (!attachToRoot) {
                                //如果attachToRoot为false,那么就将给temp设置布局参数
                                temp.setLayoutParams(params);
                            }
                        }
    
                        // 解析temp下所有的子视图
                        rInflateChildren(parser, temp, attrs, true);
    
                        // 如果root不为空 且attachToRoot为true,将temp添加到父视图中
                        if (root != null && attachToRoot) {
                            root.addView(temp, params);
                        }
    
                        // 如果root为空 或者attachToRoot为false,返回的结果就是temp
                        if (root == null || !attachToRoot) {
                            result = temp;
                        }
                    }
                ...//省略catch代码
                return result;
            }
        }
    

    上面inflate 方法中,主要有下面几步:

    1. 解析xml中的根标签;
    2. 如果是merge标签,那么就调用rInflate进行解析,rInflate会将merge标签下的所有子View直接添加到根标签中。
    3. 如果标签时普通元素,调用createViewFromTag对该元素进行解析;
    4. 调用rInflateChildren方法(实际里面调用rInflate的方法)解析所有子View,并将这些子View添加到temp下;
    5. 返回解析到的视图。

    我们从简单的地方理解,即解析单个元素的createViewFromTag,看看代码如何运行:

        View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
                boolean ignoreThemeAttr) {
            if (name.equals("view")) {
                name = attrs.getAttributeValue(null, "class");
            }
            ...//应用特殊主体的代码省略
            try {
                View view;
                ...
                if (view == null) {
                    ...
                        //传过来的控件是否包含".",不包含就是系统的控件
                        if (-1 == name.indexOf('.')) {
                            view = onCreateView(parent, name, attrs);
                        } else {
                            //否则就是自定义的控件
                            view = createView(name, null, attrs);
                        }
                }
    
                return view;
            ...//省略catch
        }
    

    createViewFromTag 会将该元素的parent及名字传过来。当这个tag的名字中没有包含“.” 时,LayoutInflater会认为这是一个内置的VIew ,例如,我们声明一个内置的控件时:

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!" />
    

    这里的TextView就是xml元素的名字,在执行inflate时就会调用onCreateView 方法来解析这个TextView 标签。当我们自定义一个View时,在xml中必须指定完整路径,例如:

    <com.huang.view.MyView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
    

    这是就会调用createView 来解析该VIew ,这两个方法中有什么不同呢?上一段的PhoneLayoutInflater 中我们知道,PhoneLayoutInflater重写了onCreateView 方法,该方法在View标签名的前面设置了前缀“android.widget” 然后在传给createView 方法进行解析。也就是说内置View和自定义View 最终都调用了createView 构造出完整路径进行解析。如果是自定义View ,那么必须写完整的路径,此时调用createView 且前缀为null 进行解析。

    LayoutInflater的createView方法

        public final View createView(String name, String prefix, AttributeSet attrs)
                throws ClassNotFoundException, InflateException {
            //1.从缓存中获取构造函数
            Constructor<? extends View> constructor = sConstructorMap.get(name);
            if (constructor != null && !verifyClassLoader(constructor)) {
                constructor = null;
                sConstructorMap.remove(name);
            }
            Class<? extends View> clazz = null;
    
            try {
                //2. 缓存中没有构造函数,
                if (constructor == null) {
                    //如果前缀不为null,构造完整的View路径,并且加载该类
                    clazz = mContext.getClassLoader().loadClass(
                            prefix != null ? (prefix + name) : name).asSubclass(View.class);
                    ...
                    //从类中获取构造函数
                    constructor = clazz.getConstructor(mConstructorSignature);
                    constructor.setAccessible(true);
                    //将构造函数加入缓存
                    sConstructorMap.put(name, constructor);
                } else {
                   //从缓存容器中获取
                }
    
                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;
            ...//省略catch
        }
    

    createView 方法相对简单,如果有前缀,那么构造View的完整 路径,并且将该类加载到虚拟机中,然后获取该类的构造函数并且缓存起来,在通过构造函数创建该VIew的对象,最后将VIew对象返回,这就是解析单个View的过程。而我们的窗口是一颗视图树,LayoutInflater 需要解析完这颗树,这个功能就交给了rInflate方法,具体代码:

        void rInflate(XmlPullParser parser, View parent, Context context,
                AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
            //1.获取树的深度,深度优先遍历
            final int depth = parser.getDepth();
            int type;
            boolean pendingRequestFocus = false;
            //2.挨个元素解析
            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)) {
                    pendingRequestFocus = true;
                    consumeChildElements(parser);
                } else if (TAG_TAG.equals(name)) {
                    parseViewTag(parser, parent, attrs);
                } else if (TAG_INCLUDE.equals(name)) {   //解析include标签 必须是子节点
                    if (parser.getDepth() == 0) {
                        throw new InflateException("<include /> cannot be the root element");
                    }
                    parseInclude(parser, context, parent, attrs);
                } else if (TAG_MERGE.equals(name)) {   //解析merge标签 必须是根节点
                    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);
                    //将解析到的VIew添加待VIewGroup 也就是他的parent
                    viewGroup.addView(view, params);
                }
            }
            ...
        }
    

    rInflate 方法通过深度优先遍历来构造视图树,没解析到一个VIew元素就会递归调用rInflate,知道这条路径下的最后一个元素,然后再回溯过来将买个元素添加到他们的parent中。通过rInflate解析后,整个视图树就构建完毕。当调用Activity的OnResume之后。我们通过setContentView设置的内容就会出现在我们的视野中。了解setContentView请看Activity的setContentView()源码分析

    参考

    《Android源码设计模式》

    相关文章

      网友评论

          本文标题:Android源码之-深入理解LayoutInflater

          本文链接:https://www.haomeiwen.com/subject/zlmmwxtx.html