【源码解读】从源码角度理解LayoutInflater工作流程

在开发中经常需要用到LayoutInflater来加载布局,尤其是在使用ListView或者RecyclerView的时候,作为一个有节操有理想的程序猿当然不能停留在使用的层次上,现在就让我们来扒一扒这个LayoutInflater是如何运作的。

本文的分析是根据6.0的源码,对于LayoutInflater,其注册过程6.0和5.0源码实现是不同的,6.0将系统服务注册单独封装到
了SystemServiceRegistry类中,更加符合SRP原则,也更加方便阅读。

一、LayoutInflater的注册、创建与获取

首先,我们知道在使用时我们可以通过以下两种方式获取到LayoutInflater对象

 LayoutInflater inflater1 = LayoutInflater.from(this);
 LayoutInflater inflater2 = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

通过查看源码,getSystemService()方法最终也是通过from方法来获取的,而from方法最终调用Context对象的getSystemService()方法,源码如下:


    //ContextThemeWrapper(Context的子类)的getSystemService方法
    @Override 
    public Object getSystemService(String name) {
        if (LAYOUT_INFLATER_SERVICE.equals(name)) {
            if (mInflater == null) {
                mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this);
            }
            return mInflater;
        }
        return getBaseContext().getSystemService(name);
    }

    //LayoutInflate的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是作为系统服务提供给我们使用的,那么我们不禁要问,它是在什么时候注册提供给我们的呢?

在上面通过源码我们已经知道from()内部是通过调用Context的getSystemService()来获取的服务,Context是抽象类,它的具体
实现类为ContextImpl,因此我们分析ContextImpl即可,其获取系统服务的方法如下:

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

    @Override
    public String getSystemServiceName(Class<?> serviceClass) {
        return SystemServiceRegistry.getSystemServiceName(serviceClass);
    }

由此可知最终是通过SystemServiceRegistry类来获取系统服务的,SystemServiceRegistry,直译过来就是系统服务注册室,因此可以很直观的认为这就是注册系统服务的地方。让我们来查看它的源码:

final class SystemServiceRegistry {
    private final static String TAG = "SystemServiceRegistry";

    // Service registry information.
    // This information is never changed once static initialization has completed.
    private static final HashMap<Class<?>, String> SYSTEM_SERVICE_NAMES =
            new HashMap<Class<?>, String>();
    private static final HashMap<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =
            new HashMap<String, ServiceFetcher<?>>();
    private static int sServiceCacheSize;

    // Not instantiable.
    private 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);
        }
}

静态代码块中的代码就是注册系统各种服务的,由此可知在虚拟机第一次加载该类的时候就就会注册各种系统服务,也包括LayoutInflater Service.通过registerService方法可知这些服务以键值对的形式存储在名为SYSTEM_SERVICE_FETCHERS的HashMap中,服务名存储在名为SYSTEM_SERVICE_NAMES的HashMap中。
SystemServiceRegistry的获取服务的代码如下:

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

    /**
     * Gets the name of the system-level service that is represented by the specified class.
     */
    public static String getSystemServiceName(Class<?> serviceClass) {
        return SYSTEM_SERVICE_NAMES.get(serviceClass);
    }

最终是通过ServiceFetcher对象的getService()方法来获取的服务。ServiceFetcher是SystemServiceRegistry的一个内部接口,
有三个实现类分别是: CachedServiceFetcher、StaticServiceFetcher、StaticOuterContextServiceFetcher

 static abstract interface ServiceFetcher<T> {
    T getService(ContextImpl ctx);
    }

在注册LayoutInflater服务时使用的是CachedServiceFetcher,因此这里只看CachedServiceFetcher的源码,其他的请自行查阅

    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);
    }

通过Fetcher的getService()方法可以知道,首先Fetcher会获取到当前Context对象的mServiceCache数组查看是否已经缓存系统服务,如果没有则创建服务并缓存,有的话就直接调用缓存好的服务对象不需要再重新创建。mServiceCache是ContextImpl中的一个数组, 用来缓存服务对象。

 final Object[] mServiceCache = SystemServiceRegistry.createServiceCache();

这是单例模式的一种实现方式,服务以键值对的形式存储在HashMap中,用户使用时只需要根据key值类获取到对应ServiceFetcher,然后通过ServiceFetcher对象的getService来获取具体的服务对象, 当第一次获取的时候回调用createService()方法创建服务对象,然后将对象缓存到一个数组中,下次再获取时直接从数组获取,这样就避免了重复创建对象,从而达到单例的效果。

回到LayoutInflater服务的创建,LayoutInflater是抽象类,其具体实现类就是PhoneLayoutInflater类,因此实际创建的就是
PhoneLayoutInflater对象。以上就是整个LayoutInflater的注册和创建、获取过程,接下来我们分析它加载布局的过程。

再次强调:本文的分析是根据6.0的源码,对于LayoutInflater,其注册过程6.0和5.0源码实现是不同的,6.0将系统服务注册单独封装到
了SystemServiceRegistry类中,更加符合SRP原则,也更加方便阅读,具体的细节请自行参阅Android源码。

二、LayoutInflater加载布局过程分析

在开发中我们都是通过调用LayoutInflater对象的inflate方法来加载布局的,无论传参如何,最终都会调用到下面的代码:

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
            }

            if (type != XmlPullParser.START_TAG) {
                throw new InflateException(parser.getPositionDescription()
                    + ": No start tag found!");
            }

            final String name = parser.getName();

            if (DEBUG) {
                System.out.println("**************************");
                System.out.println("Creating root view: "
                        + name);
                System.out.println("**************************");
            }

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

        Trace.traceEnd(Trace.TRACE_TAG_VIEW);

        return result;
    }
}

分析代码可知是通过XmlPullParser对布局文件进行解析,在第24行,得到布局根元素的名称,如果是merge标签,则调用 rInflate()
方法进行深度解析,如果不是,则在第42行调用createViewFromTag()创建该元素后调用rInflate()方法进行解析。

createViewFromTag方法源码如下:

 View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
        if (name.equals("view")) {
            name = attrs.getAttributeValue(null, "class");
        }

        // Apply a theme wrapper, if allowed and one is specified.
        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();
        }

        if (name.equals(TAG_1995)) {
            // Let's party like it's 1995!
            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 {
                    if (-1 == name.indexOf('.')) {
                        view = onCreateView(parent, name, attrs);
                    } else {
                        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);
            ie.initCause(e);
            throw ie;

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

39行之前的代码可以忽略,直接看39行的判断语句,这里通过判断name中有没有”.”来确定元素是内置控件还是自定义控件,如果不包含,则是内置控件,调用onCreateView方法进行创建;自定义控件需要写全类名,因此会包含”.”, 调用createView()进行创建。

上面我们提到了PhoneLayoutInflater对象,它主要就是覆写了onCreateView方法,为内置控件添加上包名,其代码如下:

public class PhoneLayoutInflater extends LayoutInflater {
    private static final String[] sClassPrefixList = {
        "android.widget.",
        "android.webkit.",
        "android.app."
    };

    /**
     * Instead of instantiating directly, you should retrieve an instance
     * through {@link Context#getSystemService}
     *
     * @param context The Context in which in which to find resources and other
     *                application-specific things.
     *
     * @see Context#getSystemService
     */
    public PhoneLayoutInflater(Context context) {
        super(context);
    }

    protected PhoneLayoutInflater(LayoutInflater original, Context newContext) {
        super(original, newContext);
    }

    /** Override onCreateView to instantiate names that correspond to the
        widgets known to the Widget factory. If we don't find a match,
        call through to our super class.
    */
    @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;
                }
            } catch (ClassNotFoundException e) {
                // In this case we want to let the base class take a crack
                // at it.
            }
        }

        return super.onCreateView(name, attrs);
    }

    public LayoutInflater cloneInContext(Context newContext) {
        return new PhoneLayoutInflater(this, newContext);
    }
}

通过代码可以看出最终还是调用了createView()方法,并为内置控件添加前缀,”android.widget.”,”android.webkit.”或者”android.app.”构成完整的全类名。

//根据完整路径的类名,通过反射构建View对象
public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
        //1.从缓存中获取构造函数
        Constructor<? extends View> constructor = sConstructorMap.get(name);
        Class<? extends View> clazz = null;

        try {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
            //2.如果构造函数为空且前缀不为空,构造完整的View路径并加载该类
            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);
                    }
                }
                //3.从Class对象中获取构造函数
                constructor = clazz.getConstructor(mConstructorSignature);
                constructor.setAccessible(true);
                sConstructorMap.put(name, constructor);
            } else {
                // If we have a filter, apply it to cached constructor
                if (mFilter != null) {
                    // Have we seen this name before?
                    Boolean allowedState = mFilterMap.get(name);
                    if (allowedState == null) {
                        // New class -- remember whether it is allowed
                        clazz = mContext.getClassLoader().loadClass(
                                prefix != null ? (prefix + name) : name).asSubclass(View.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);
            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;

        } 
        //。。。。代码省略
    }

上面我们已经提到,无论是否为merge标签,最终都会调用到rInflate()方法,因为Android的窗体是一棵视图树,我们需要通过
rInflate()方法来解析完这棵视图树。具体代码如下:

    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)) {
                parseRequestFocus(parser, parent);
            } 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标签,因为merge必须为根视图,因此如果这里出现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内部还是调用rInflate方法。通过递归调用进行深度优先遍历解析
                rInflateChildren(parser, view, attrs, true);
                //将解析到的View添加到ViewGroup中
                viewGroup.addView(view, params);
            }
        }

        if (finishInflate) {
            parent.onFinishInflate();
        }
    }

通过上面代码可以看出,rInflate通过递归调用遍历解析每个元素,每次递归完成则将这个View添加到它的父元素中,最终将所有
的元素都添加到了root布局中去,这样递归完成后就形成了完整的DOM树。至此inflate结束,我们就得到了相应的View。

另外关于attachToRoot参数,这里引用郭霖大神博客里的讲解:

  1. 如果root为null,attachToRoot将失去作用,设置任何值都没有意义。
  2. 如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root。
  3. 如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,当该view被添加到父view当中时,这些layout属性会自动生效。
  4. 在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true。

小伙伴们可以通过阅读源码和具体的使用来验证上述结论,这里不再赘述。

OK,到这里LayoutInflate的分析就结束, 相信读完源码的童鞋应该也会对LayoutInflater的内部机制有了一个大致的了解,以后再使用的时候无论遇到什么问题应该都能解决了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值