Android源码之-深入理解LayoutInflater

前言

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源码设计模式》

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

推荐阅读更多精彩内容