LayoutInflater 的from传入的context不同会有什么区别?

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sumsear/article/details/79610038
LayoutInflater.from(context);

在Android开发中经常用到,很多年前想了一下,这里的from方法中传递的Context用Activity和Application会不会有什么不同。

粗略的看一下源码,发现在from函数中调用的是一个context的抽象方法getSystemService,在ContextWrapper类的实现中又是调用的自己的成员属性mBase的getSystemService方法。根据源码我们发现mBase是在ActivityThread类的performLaucher方法创建Application和Activity的时候通过attach函数传递的一个ContextImpl实例,从而我们发现getSystemService方法的实现位于app包下的ContextImpl中,底下其实还有很多玄机。言归正传,我今天要记录的不是getSystemService是怎么实现的,而是LayoutInflater的from方法传递Application和Activity有什么不同。

 /**
     * Obtains the LayoutInflater from the given context.
     */
    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;
    }

如果只看到这里会发现from方法中传递Application和Activity应该是一样。如果只看到这里就做出判断就被google给耍了,实际上在Activity的父类ContextThemeWrapper中实现了该方法;

 @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);
    }
问题就在于此,当我们传递的是Activity的时候,会触发这一步操作。这一步其实就是利用原型模式创建了一个LayoutInflater实例并且将实例中的Context替换成当前的Context。很明显当前的Context是包含有主题等与UI相关的属性。


猜你喜欢

转载自blog.csdn.net/sumsear/article/details/79610038