Android XML布局文件解析过程源码解析

Posted 一口仨馍

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android XML布局文件解析过程源码解析相关的知识,希望对你有一定的参考价值。

我们知道,在Activity#setContentView()中会调用PhoneWindow#setContentView()。而在PhoneWindow#setContentView()中有这么一句mLayoutInflater.inflate(layoutResID, mContentParent)。这行代码的作用是将我们的activity_main.xml填充到mContentParent中去。详见:setContentView源码解析。在写adapter的时候,也经常写mInflater.inflate(layoutResID, parent,false)。那么,这行代码怎么就将xml文件转换成了View或者ViewGroup了呢?

获取LayoutInflater对象无非以下两种方式:

  1. LayoutInflater.from(Context context);
  2. LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

其实这俩是同一种方式,首先看下LayoutInflater#from()

源码位置:frameworks/base/core/java/android/view/LayoutInflater.java

LayoutInflater#from()

    public static LayoutInflater from(Context context) 
        LayoutInflater LayoutInflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (LayoutInflater == null) 
            throw new AssertionError("LayoutInflater not found.");
        
        return LayoutInflater;
    

第一种获取LayoutInflater对象的方式,不过就是对第二种方式的一个简单封装。实际上还是一回事。Context的实现类是ContextImpl,跟进。

源码位置:frameworks/base/core/java/android/app/ContextImpl.java

ContextImpl#getSystemService()

    @Override
    public Object getSystemService(String name) 
        return SystemServiceRegistry.getSystemService(this, name);
    

跟进。

源码位置:frameworks/base/core/java/android/app/SystemServiceRegistry.java

SystemServiceRegistry#getSystemService()

    public static Object getSystemService(ContextImpl ctx, String name) 
        ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
        return fetcher != null ? fetcher.getService(ctx) : null;
    

直接从全局变量SYSTEM_SERVICE_FETCHERS中依据名字就get到了fetcher,之后依据fetcher直接get到了LayoutInflater对象。大写的懵B~原来啊,在SystemServiceRegistry中有个静态代码块,先看下这部分。

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

    private static <T> void registerService(String serviceName, Class<T> serviceClass,
            ServiceFetcher<T> serviceFetcher) 
        SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);
        SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
    

    static abstract class CachedServiceFetcher<T> implements ServiceFetcher<T> 
        private final int mCacheIndex;

        public CachedServiceFetcher() 
            mCacheIndex = sServiceCacheSize++;
        

        @Override
        @SuppressWarnings("unchecked")
        public final T getService(ContextImpl ctx) 
            final Object[] cache = ctx.mServiceCache;
            synchronized (cache) 
                // Fetch or create the service.
                Object service = cache[mCacheIndex];
                if (service == null) 
                    service = createService(ctx);
                    cache[mCacheIndex] = service;
                
                return (T)service;
            
        

        public abstract T createService(ContextImpl ctx);
    

这里连续贴了两个方法和一个抽象内部类CachedServiceFetcher。由于在抽象方法CachedServiceFetcher#createService()的具体实现中返回的是PhoneLayoutInflater,所以后文中使用的一直是PhoneLayoutInflater的对象。获取LayoutInflater对象(其实是其子类PhoneLayoutInflater对象)之后,调用LayoutInflater#inflate()。跟进。

源码位置:frameworks/base/core/java/android/view/LayoutInflater.java

LayoutInflater#inflate()

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) 
        return inflate(resource, root, root != null);
    

这里以setContentView中的mLayoutInflater.inflate(layoutResID, mContentParent)为例,顺带也会讲解adapter中mInflater.inflate(layoutResID,null)这种情况。也就是root参数为null和不为null两种情况。root==null,则第三个参数为false.root!=null,则第三个参数为true。跟进。

LayoutInflater#inflate()

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) 
        final Resources res = getContext().getResources();
        final XmlResourceParser parser = res.getLayout(resource);
        try 
            return inflate(parser, root, attachToRoot);
         finally 
            parser.close();
        
    

跟进。

LayoutInflater#inflate()

    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) 
        synchronized (mConstructorArgs) 
            ...
            View result = root;
            try 
                ...
                // 获取根节点的字符串,例如LinearLayout
                final String name = parser.getName();
                // 根节点merge开头
                if (TAG_MERGE.equals(name)) 
                    ...
                 else 
                    // 创建根视图View
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                    ViewGroup.LayoutParams params = null;
                    if (root != null) 
                        // 获取LayoutParams
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) 
                            // 应用LayoutParams到根节点View
                            temp.setLayoutParams(params);
                        
                    
                    // 遍历解析子View,并添加到根节点temp中
                    rInflateChildren(parser, temp, attrs, true);
                    // root不为空,直接将根节点View添加到root中
                    if (root != null && attachToRoot) 
                        root.addView(temp, params);
                    
                    // root等于null,直接返回根节点temp
                    if (root == null || !attachToRoot) 
                        result = temp;
                    
                
            catch (Exception e) 
                ...
                
            return result;
        
                           

上面每一步都有注释,下面重点看下生成根节点View的createViewFromTag()和遍历生成子View的rInflateChildren()方法。

LayoutInflater#createViewFromTag()

    private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) 
        return createViewFromTag(parent, name, context, attrs, false);
    

    View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) 
        ...
        if (-1 == name.indexOf('.')) 
            view = onCreateView(parent, name, attrs);
         else 
            view = createView(name, null, attrs);
        
        ...
        return view;
    

跟进。

LayoutInflater#createView()

    public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException 
        Constructor<? extends View> constructor = sConstructorMap.get(name);
        Class<? extends View> clazz = null;
        try 
            if (constructor == null) 
                clazz = mContext.getClassLoader().loadClass(
                        prefix != null ? (prefix + name) : name).asSubclass(View.class);
                ...
                constructor = clazz.getConstructor(mConstructorSignature);
                constructor.setAccessible(true);
                sConstructorMap.put(name, constructor);
             else 
                ...
            
            final View view = constructor.newInstance(args);
            return view;
         catch (Exception e) 
            ...
           
        

sConstructorMap是个HashMap<String, Constructor<? extends View>>对象。首先依据根节点的名字,例如LinearLayout去查找缓存的构造器,如果是第一次执行,肯定返回null。如果返回为null,则通过反射出构造方法,并强制设置可访问,之后存进sConstructorMap中。如果缓存中有构造器,那么直接取出。最后调用newInstance反射出根节点View实例。得到根节点View实例之后,接着设置属性,最后调用rInflateChildren()遍历创建子View。跟进。

LayoutInflater#rInflateChildren()

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

parent参数是根节点View。这里只是简单转发给rInflate()方法处理。跟进。

LayoutInflater#rInflateChildren()

    void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException 
        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();
            if (TAG_REQUEST_FOCUS.equals(name)) 
                ...
            
            ...
             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);
                viewGroup.addView(view, params);
            
        
        if (finishInflate) 
            parent.onFinishInflate();
        
    

遍历体现在While循环上,name为子节点View的名称,例如:TextView,RelativeLayout等。几个以tag、include等开头的子节点走最上面几个if的逻辑,我们的重点在于寻常View走的else逻辑。可以看到:首先,和创建根节点View调用同一个方法createViewFromTag()创建子View,紧接着设置子View的参数,然后调用递归调用rInflateChildren()方法再去测量子节点的所有View,最后才将子节点添加到父布局,这个父布局可能是根节点,也可能是某个子节点。遍历结束之后,所有子View也添加到布局当中并设置好相应的布局参数。

至此,LayoutInflater.from().inflate()源码解析结束~

更多Framework源码解析,请移步 Framework源码解析系列[目录]

以上是关于Android XML布局文件解析过程源码解析的主要内容,如果未能解决你的问题,请参考以下文章

Android中measure过程WRAP_CONTENT详解以及xml布局文件解析流程浅析(上

源码解析Android中View的measure量算过程

Android 使用WindowManager实现悬浮窗及源码解析

Android 使用WindowManager实现悬浮窗及源码解析

使用 DOM 解析 Android XML 布局文件

android中XML文件是如何解析成View