LayoutInflater源码分析(二)

上一篇LayoutInflater源码分析(一)我们分析了LayoutInflater的from()方法,这节我们来分析一下inflate()方法。

view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_vip, parent, false);

最终都会进入到如下代码:

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;

            //令人窒息操作part one~
            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!");
                }

                final String name = parser.getName();
                
                //去掉部分代码
                //令人窒息操作part two ~
                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 {
                     //令人窒息操作part three ~
                    // 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);
                        }
                    }

                    if (DEBUG) {
                        System.out.println("-----> start inflating children");
                    }

                    // 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) {
                final InflateException ie = new InflateException(e.getMessage(), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } catch (Exception e) {
                final InflateException ie = new InflateException(parser.getPositionDescription()
                        + ": " + e.getMessage(), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } finally {
                // Don't retain static reference on context.
                mConstructorArgs[0] = lastContext;
                mConstructorArgs[1] = null;

                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }

            return result;
        }
    }

通过代码和注释我们可以看到,拿到XmlResourceParser parser是用于节点的解析。

比如part one 从头到尾遍历xml文件的标签,直到
文档结束才跳出循环。如果该xml没有开始标签,则抛异常。

part two 讲的是什么呢?TAG_MERGE="merge",如果读到的标签是merge,判断是否有父View,没有则抛异常,有则跳转到rInflate()解析merge的xml。

part three就是当前的标签没有其他子xml,要直接解析啦。关键方法就是createViewFromTag()方法了。

(一)rInflate()解析

void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
        //获取该xml的深度 ~~
        final int depth = parser.getDepth();
        int type;
        
        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();
            //判断标签是否为requestFocus[1]。requestFocus标签于指定屏幕内的焦点View
            if (TAG_REQUEST_FOCUS.equals(name)) {
                parseRequestFocus(parser, parent);
            //判断标签是否为tag。
            //设置一个文本标签。可以通过View.getTag()或 for with View.findViewWithTag()检索含有该标签字符串的View。
            //但一般最好通过ID来查询View,因为它的速度更快,并且允许编译时类型检查。
            } else if (TAG_TAG.equals(name)) {
                parseViewTag(parser, parent, attrs);
            //判断标签是否为include。
            } else if (TAG_INCLUDE.equals(name)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            //判断标签是否为merge。如果是,则直接抛出异常,因为Merge必须为根元素,也就是深度为0的节点。
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException("<merge /> must be the root element");
            } else {
                //没啥奇奇怪怪标签了。又出现了这个createViewFromTag()方法。这个方法其实就是根据标签(节点名)称创建View。
                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添加进Parent布局
                viewGroup.addView(view, params);
            }
        }
        //通知父View,解析完成。
        if (finishInflate) {
            parent.onFinishInflate();
        }
    }

我们点击进入rInflateChildren()方法,发现其实也是调用的rInflate()方法:

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

(二)createViewFromTag()解析

View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
        //解析view标签,注意哦,是view不是View,这个标签一般大家不太常用。[2]
        if (name.equals("view")) {
            name = attrs.getAttributeValue(null, "class");
        }

         //如果需要该标签与主题相关,需要对context进行包装,将主题信息加入context包装类ContextWrapper
        //好吧其实我不知道这个是什么鬼,哈哈哈
        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();
        }
        //TAG_1995="blink"
        if (name.equals(TAG_1995)) {
            //BlinkLayou继承自FrameLayout,它包裹的内容会一直闪烁。[3]
            return new BlinkLayout(context, attrs);
        }
        
        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 && mPrivateFactory != null) {
                view = mPrivateFactory.onCreateView(parent, name, context, attrs);
            }

            if (view == null) {
                final Object lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = context;
                try {
                    //indexOf()的用法:
                    //返回字符中indexof(string)中字串string在父串中首次出现的位置,从0开始!没有返回-1。
                    //下面判断语句是对自定义View和原生的控件进行判断。如果name中包含.即为自定义View,否则为原生的View控件
                    //例如:<Button>
                    if (-1 == name.indexOf('.')) {
                        view = onCreateView(parent, name, attrs);
                    } else {
                        //自定义控件,例如: <com.xxx.xxx.MyView>
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }

            return view;
        } catch (InflateException e) {
            throw e;

        } catch (ClassNotFoundException e) {
            final InflateException ie = new InflateException(attrs.getPositionDescription()
                    + ": Error inflating class " + name, e);
            ie.setStackTrace(EMPTY_STACK_TRACE);
            throw ie;

        } catch (Exception e) {
            final InflateException ie = new InflateException(attrs.getPositionDescription()
                    + ": Error inflating class " + name, e);
            ie.setStackTrace(EMPTY_STACK_TRACE);
            throw ie;
        }
    }

[2]view相当于所有控件标签的父类一样,可以设置class属性,这个属性会决定view这个节点会变成什么控件。

 <view
        class="RelativeLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></view>

[3]blink这个标签很有好玩,大家可以自己试试下面的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <blink
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="一闪一闪亮晶晶"
            android:textSize="18sp"
            android:textColor="@android:color/holo_orange_light"
            />

    </blink>
</LinearLayout>

我们看到mFactory 和mFactory2 ,他们的类型是Factory和Factory2。而实际上Factory和Factory2都是一个接口,需要自己实现,并且Factory2继承自Factory,从而扩展出一个参数,就是增加了该节点的父View。

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

那么这两个Factory是用来干嘛的呢?Factory和Factory2其实LayoutInflater解析View时的一种扩展实现,可以额外的对View处理,设置Factory和Factory2需要通过setFactory()或者setFactory2()来实现。

有没有个具体例子演示一下?鸿洋大神给过一个例子,我稍作修改了代码。xml中有一个TextView,但是经过下面代码修改,将TextView变成了Button:

public class MainActivity extends AppCompatActivity
{
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        LayoutInflaterCompat.setFactory(LayoutInflater.from(this), new LayoutInflaterFactory()
        {
            @Override
            public View onCreateView(View parent, String name, Context context, AttributeSet attrs)
            {
                //这这这,小哥哥我在这~
                if (name.equals("TextView"))
                   {
                      Button button = new Button(context, attrs);
                      return button;
                   }
                }

                return null;
            }
        });
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

具体查看:Android 探究 LayoutInflater setFactory

需要强调一点,LayoutInflater内部定义了一个boolean类型的mFactorySet开关,其值默认值为false,当我们调用过setFactory()或者是setFactory2()后mFactorySet为true,若我们再次调用这俩方法时会抛出异常,也就是说每一个LayoutInflater实例对象只能赋值一次Factory,若再想赋成其他值只能通过反射先把mFactorySet的值置为false防止抛异常。具体的大家可以去看setFactory()和setFactory2()代码,我这边不叙述了。

我们前面代码标注过,如果是原生控件,那它走:

view = onCreateView(parent, name, attrs);

我们点击方法看一下:

protected View onCreateView(View parent, String name, AttributeSet attrs)
            throws ClassNotFoundException {
        return onCreateView(name, attrs);
    }

再点进去onCreateView()看下:

protected View onCreateView(String name, AttributeSet attrs)
            throws ClassNotFoundException {
        return createView(name, "android.view.", attrs);
    }

我们可以看到标签名自动帮我们加上了"android.view",再点进createView()方法,发现最终该原生控件走的是和自定义控件一样的createView()方法。这个方法有点长,大家坚持一会儿,本章快结束了。

public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {

         // 以View的name为key, 查询构造函数的缓存map中是否已经存在该View的构造函数.
        Constructor<? extends View> constructor = sConstructorMap.get(name);
         //verifyClassLoader()判断ClassLoader是否安全
        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) {
               // 如果传入的第二个参数prefix为null,就说明name是完整的包名,是自定义控件,直接反射加载自定义View。
               //如果第二个参数不为 null,就由前缀+name组成完整的类名。
                clazz = mContext.getClassLoader().loadClass(
                        prefix != null ? (prefix + name) : name).asSubclass(View.class);
                 // 如果有自定义的过滤器并且加载到字节码,则通过过滤器判断是否允许加载该View
                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 (mFilter != null) {
                    // 过滤的map是否包含了此类名
                    Boolean allowedState = mFilterMap.get(name);
                   
                    if (allowedState == null) {
                         //加载Class对象操作
                        // New class -- remember whether it is allowed
                        clazz = mContext.getClassLoader().loadClass(
                                prefix != null ? (prefix + name) : name).asSubclass(View.class);
                        //判断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[] args = mConstructorArgs;
            args[1] = attrs;
            //如果过滤器不存在,直接实例化该View
            final View view = constructor.newInstance(args);
            //如果View属于ViewStub那么需要给ViewStub设置一个克隆过的LayoutInflater
            if (view instanceof ViewStub) {
                // Use the same context when inflating ViewStub later.
                final ViewStub viewStub = (ViewStub) view;
                viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
            }
            return view;

        } catch (NoSuchMethodException e) {
            final InflateException ie = new InflateException(attrs.getPositionDescription()
                    + ": Error inflating class " + (prefix != null ? (prefix + name) : name), e);
            ie.setStackTrace(EMPTY_STACK_TRACE);
            throw ie;

        } catch (ClassCastException e) {
            // If loaded class is not a View subclass
            final InflateException ie = new InflateException(attrs.getPositionDescription()
                    + ": Class is not a View " + (prefix != null ? (prefix + name) : name), e);
            ie.setStackTrace(EMPTY_STACK_TRACE);
            throw ie;
        } catch (ClassNotFoundException e) {
            // If loadClass fails, we should propagate the exception.
            throw e;
        } catch (Exception e) {
            final InflateException ie = new InflateException(
                    attrs.getPositionDescription() + ": Error inflating class "
                            + (clazz == null ? "<unknown>" : clazz.getName()), e);
            ie.setStackTrace(EMPTY_STACK_TRACE);
            throw ie;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
    }

具体的注释我写在代码里了,大家自行查阅。希望看完文章,大家花个两分钟思考一下LayoutInflate的一些主要方法的作用是什么、xml是怎么转变成view的。有机会我会再开一篇文章,讲讲LayoutInflater的一点实战内容。

感谢:Android 中LayoutInflater(布局加载器)系列博文说明等网络各种博客。欢迎纠错,互相学习~

[1]

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

推荐阅读更多精彩内容