LayoutInflater.Factory使用及源码解析

1,975 阅读7分钟

PS:原文首发于微信公众号:躬行之(jzman-blog)

LayoutInflater.Factory 是提供给你的一个加载布局使用的回调接口(Hook),可以使用 LayoutInflater.Factory 来自定义布局文件,实际上就是可以在 LayoutInflater.Factory 的回调中可以根据对应的 Tag 来修改某个 View,然后返回出去,LayoutInflater.Factory 源码如下:

// LayoutInflater.java
public interface Factory {
    /**
     * @param name Tag名称,如TextView
     * @param context 上下文环境
     * @param attrs Xml属性
     *
     * @return View 新创建的View,如果返回null,则Hook无效
     */
    public View onCreateView(String name, Context context, AttributeSet attrs);
}

public interface Factory2 extends Factory {
    // since API 11,多添加了一个参数parent
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs);
}

已知在布局文件加载时调用 createViewFromTag 方法创建 View 的,它会依次判断 mFactory、mFactory2、mPrivateFactory 是否 为null,如果创建出的 View 不为null,则直接返回该 View,源码如下:

// LayoutInflater.java
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,boolean ignoreThemeAttr) {
    //...
  
    View view;
    // 依次判断mFactory、mFactory2、mPrivateFactory是否为null,如果创建出的View不为null,则直接返回该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);
    }
    
    // 从布局文件中解析出View
    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;
   // ...
}

前面知道 LayoutInflater.Fractory 是用来对布局文件进行修改的,此处这样做肯定是某个地方已经设置 mFactory 或 mFactory2,查看源码知 setFactory 和 setFactory2 在 LayoutInflaterCompat 被调用,LayoutInflaterCompat 为了达到兼容的目的,对 setFactory 和 setFactory2 进行了处理,其中 setFactory 已经被废弃,源码如下:

// LayoutInflaterCompat.java
@Deprecated
public static void setFactory(
        @NonNull LayoutInflater inflater, @NonNull LayoutInflaterFactory factory) {
    if (Build.VERSION.SDK_INT >= 21) {
        inflater.setFactory2(factory != null ? new Factory2Wrapper(factory) : null);
    } else {
        final LayoutInflater.Factory2 factory2 = factory != null
                ? new Factory2Wrapper(factory) : null;
        inflater.setFactory2(factory2);

        final LayoutInflater.Factory f = inflater.getFactory();
        if (f instanceof LayoutInflater.Factory2) {
            // The merged factory is now set to getFactory(), but not getFactory2() (pre-v21).
            // We will now try and force set the merged factory to mFactory2
            forceSetFactory2(inflater, (LayoutInflater.Factory2) f);
        } else {
            // Else, we will force set the original wrapped Factory2
            forceSetFactory2(inflater, factory2);
        }
    }
}

public static void setFactory2(
        @NonNull LayoutInflater inflater, @NonNull LayoutInflater.Factory2 factory) {
    inflater.setFactory2(factory);

    if (Build.VERSION.SDK_INT < 21) {
        final LayoutInflater.Factory f = inflater.getFactory();
        if (f instanceof LayoutInflater.Factory2) {
            // The merged factory is now set to getFactory(), but not getFactory2() (pre-v21).
            // We will now try and force set the merged factory to mFactory2
            forceSetFactory2(inflater, (LayoutInflater.Factory2) f);
        } else {
            // Else, we will force set the original wrapped Factory2
            forceSetFactory2(inflater, factory);
        }
    }
}

从 setFactory2 使用了了 forceSetFactory2 方法里面通过反射强制设置了 LayoutInflater 的 mFactory2 属性值,源码如下:

// LayoutInflaterCompat.java
private static void forceSetFactory2(LayoutInflater inflater, LayoutInflater.Factory2 factory) {
    if (!sCheckedField) {
        try {
            sLayoutInflaterFactory2Field = LayoutInflater.class.getDeclaredField("mFactory2");
            sLayoutInflaterFactory2Field.setAccessible(true);
        } catch (NoSuchFieldException e) {
            Log.e(TAG, "forceSetFactory2 Could not find field 'mFactory2' on class "
                    + LayoutInflater.class.getName()
                    + "; inflation may have unexpected results.", e);
        }
        sCheckedField = true;
    }
    if (sLayoutInflaterFactory2Field != null) {
        try {
            sLayoutInflaterFactory2Field.set(inflater, factory);
        } catch (IllegalAccessException e) {
            Log.e(TAG, "forceSetFactory2 could not set the Factory2 on LayoutInflater "
                    + inflater + "; inflation may have unexpected results.", e);
        }
    }
}

那么 LayoutInflater 的 setFactory2 方法在哪调用的呢,查看源码知分别在 AppCompatDelegateImpl 和 Fragment 里面调用过,这里以 AppCompatDelegateImpl 为例来进行分析,查看源码可知,AppCompatDelegateImpl 里面有个方法 installViewFactory 里面统一设置了 LayoutInflater.Factory,源码如下:

// AppCompatDelegateImpl.java
@Override
public void installViewFactory() {
    LayoutInflater layoutInflater = LayoutInflater.from(mContext);
    if (layoutInflater.getFactory() == null) {
        // 统一设置LayoutInflater.Factory
        LayoutInflaterCompat.setFactory2(layoutInflater, this);
    } else {
         // 如果自行设置了LayoutInflater.Factory则失去新特性的支持并打印日志
        if (!(layoutInflater.getFactory2() instanceof AppCompatDelegateImpl)) {
            Log.i(TAG, "The Activity's LayoutInflater already has a Factory installed"
                    + " so we can not install AppCompat's");
        }
    }
}

继续查看 installViewFactory 方法是在 AppCompatActivity 的 onCreate 方法中调用的,源码如下:

// AppCompatActivity.java
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    final AppCompatDelegate delegate = getDelegate();
    // AppCompatActivity统一设置LayoutInflater.Factory
    delegate.installViewFactory();
    delegate.onCreate(savedInstanceState);
    if (delegate.applyDayNight() && mThemeId != 0) {
        if (Build.VERSION.SDK_INT >= 23) {
            onApplyThemeResource(getTheme(), mThemeId, false);
        } else {
            setTheme(mThemeId);
        }
    }
    super.onCreate(savedInstanceState);
}

从 Android 5.0 开始 Google 添加了很多新特性,进而为了能够向前兼容,又推出了 support.v7 包,里面就有上文中提到的 AppcompatActivity,这也就是之前 createViewFromTag 中要进行 mFactory1、mFactory2 等的判断,先从默认 Factory 实现的 onCreateView 方法获取 View,如果没有设置过 LayoutInflater.Factory 则直接从布局文件中解析出 View。

因为一般创建的 Activity 都是继承 AppCompatActivity,也就默认设置了 LayoutInflater.Factory,当使用 LayoutInflater 加载布局文件时就会调用其 onCreateView 方法,查看源码知 AppCompatDelegateImpl 和 Activity 都实现了 LayoutInflater.Factory2 接口,这里查看 AppCompatDelegateImpl 中的具体实现,源码如下:

/**
 * From {@link LayoutInflater.Factory2}.
 */
@Override
public final View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
    return createView(parent, name, context, attrs);
}

/**
 * From {@link LayoutInflater.Factory2}.
 */
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
    return onCreateView(null, name, context, attrs);
}

可知最终调用的是 AppCompatDelegateImpl 中的 createView 方法,源码如下:

// AppCompatDelegateImpl.java
@Override
public View createView(View parent, final String name, @NonNull Context context,
        @NonNull AttributeSet attrs) {
    if (mAppCompatViewInflater == null) {
        TypedArray a = mContext.obtainStyledAttributes(R.styleable.AppCompatTheme);
        String viewInflaterClassName =
                a.getString(R.styleable.AppCompatTheme_viewInflaterClass);
        if ((viewInflaterClassName == null)
                || AppCompatViewInflater.class.getName().equals(viewInflaterClassName)) {
            // Either default class name or set explicitly to null. In both cases
            // create the base inflater (no reflection)
            mAppCompatViewInflater = new AppCompatViewInflater();
        } else {
            try {
                Class viewInflaterClass = Class.forName(viewInflaterClassName);
                mAppCompatViewInflater =
                        (AppCompatViewInflater) viewInflaterClass.getDeclaredConstructor()
                                .newInstance();
            } catch (Throwable t) {
                Log.i(TAG, "Failed to instantiate custom view inflater "
                        + viewInflaterClassName + ". Falling back to default.", t);
                mAppCompatViewInflater = new AppCompatViewInflater();
            }
        }
    }

    boolean inheritContext = false;
    if (IS_PRE_LOLLIPOP) {
        inheritContext = (attrs instanceof XmlPullParser)
                // If we have a XmlPullParser, we can detect where we are in the layout
                ? ((XmlPullParser) attrs).getDepth() > 1
                // Otherwise we have to use the old heuristic
                : shouldInheritContext((ViewParent) parent);
    }
    // 关键位置
    return mAppCompatViewInflater.createView(parent, name, context, attrs, inheritContext,
            IS_PRE_LOLLIPOP, /* Only read android:theme pre-L (L+ handles this anyway) */
            true, /* Read read app:theme as a fallback at all times for legacy reasons */
            VectorEnabledTintResources.shouldBeUsed() /* Only tint wrap the context if enabled */
    );
}

上面代码中都是先获取定义的属性集合,然后看有没有自定的 Inflater,如果自定义了就根据完整类名反射创建出 AppCompatViewInflater 对象,反之则创建默认的 AppCompatViewInflater,最后调用对应 Inflater 的 createView 方法。

看到这里,明明可以直接使用 AppCompatViewInflater 就可以了,为什么还要这么繁琐,从这里就可以看出这里由很强的扩展性,可以自定义 Inflater 来替换官方提供的 AppCompatViewInflater,继续查看 AppCompatViewInflater 的 createView 方法,源码如下:

// AppCompatViewInflater.java
final View createView(View parent, final String name, @NonNull Context context,
        @NonNull AttributeSet attrs, boolean inheritContext,
        boolean readAndroidTheme, boolean readAppTheme, boolean wrapContext) {
    final Context originalContext = context;

    // We can emulate Lollipop's android:theme attribute propagating down the view hierarchy
    // by using the parent's context
    if (inheritContext && parent != null) {
        context = parent.getContext();
    }
    if (readAndroidTheme || readAppTheme) {
        context = themifyContext(context, attrs, readAndroidTheme, readAppTheme);
    }
    if (wrapContext) {
        context = TintContextWrapper.wrap(context);
    }

    View view = null;

    // We need to 'inject' our tint aware Views in place of the standard framework versions
    switch (name) {
        case "TextView":
            view = createTextView(context, attrs);
            verifyNotNull(view, name);
            break;
        case "ImageView":
            view = createImageView(context, attrs);
            verifyNotNull(view, name);
            break;
        case "Button":
            view = createButton(context, attrs);
            verifyNotNull(view, name);
            break;
        case "EditText":
            view = createEditText(context, attrs);
            verifyNotNull(view, name);
            break;
        case "Spinner":
            view = createSpinner(context, attrs);
            verifyNotNull(view, name);
            break;
        case "ImageButton":
            view = createImageButton(context, attrs);
            verifyNotNull(view, name);
            break;
        case "CheckBox":
            view = createCheckBox(context, attrs);
            verifyNotNull(view, name);
            break;
        case "RadioButton":
            view = createRadioButton(context, attrs);
            verifyNotNull(view, name);
            break;
        case "CheckedTextView":
            view = createCheckedTextView(context, attrs);
            verifyNotNull(view, name);
            break;
        case "AutoCompleteTextView":
            view = createAutoCompleteTextView(context, attrs);
            verifyNotNull(view, name);
            break;
        case "MultiAutoCompleteTextView":
            view = createMultiAutoCompleteTextView(context, attrs);
            verifyNotNull(view, name);
            break;
        case "RatingBar":
            view = createRatingBar(context, attrs);
            verifyNotNull(view, name);
            break;
        case "SeekBar":
            view = createSeekBar(context, attrs);
            verifyNotNull(view, name);
            break;
        default:
            view = createView(context, name, attrs);
    }

    if (view == null && originalContext != context) {
        // 如果不能根据name创建出View,则根据name去用反射去创建View
        view = createViewFromTag(context, name, attrs);
    }

    if (view != null) {
        checkOnClickListener(view, attrs);
    }
    return view;
}

上述代码根据组件的名称将 app 下面的组件替换成了对应兼容版本的组件,如 TextView 替换成了 AppCompatTextView,如果不能根据 name 创建出 View,则调用 createViewFromTag 去创建 View,源码如下:

// AppCompatViewInflater.java
private View createViewFromTag(Context context, String name, AttributeSet attrs) {
    if (name.equals("view")) {
        name = attrs.getAttributeValue(null, "class");
    }

    try {
        mConstructorArgs[0] = context;
        mConstructorArgs[1] = attrs;
        // 如果name中没有出现点号,则尝试添加系统组件前缀
        if (-1 == name.indexOf('.')) {
            for (int i = 0; i < sClassPrefixList.length; i++) {
                final View view = createViewByPrefix(context, name, sClassPrefixList[i]);
                if (view != null) {
                    return view;
                }
            }
            return null;
        } else {// 不添加前缀
            return createViewByPrefix(context, name, null);
        }
    } catch (Exception e) {
        return null;
    } finally {
        // Don't retain references on context.
        mConstructorArgs[0] = null;
        mConstructorArgs[1] = null;
    }
}

可知这里的 createViewFromTag 发明就是尝试在 name 上去添加系统组件的前缀,最后都要去调用 createViewByPrefix 去创建 View,createViewByPrefix 里面使用过反射去创建对象,源码如下:

// AppCompatViewInflater.java
private View createViewByPrefix(Context context, String name, String prefix)
            throws ClassNotFoundException, InflateException {
    // 借鉴缓存的使用
    Constructor<? extends View> constructor = sConstructorMap.get(name);
    try {
        if (constructor == null) {
            Class<? extends View> clazz = context.getClassLoader().loadClass(
                    prefix != null ? (prefix + name) : name).asSubclass(View.class);

            constructor = clazz.getConstructor(sConstructorSignature);
            sConstructorMap.put(name, constructor);
        }
        constructor.setAccessible(true);
        return constructor.newInstance(mConstructorArgs);
    } catch (Exception e) {
        return null;
    }
}

这里除了使用反射去创建 View 之外,为了降低性能的消耗还使用 HaskMap 做了 View 的构造方法的缓存,先从缓存中取对应的构造方法,缓存中不存在对应的构造方法实例才会去反射构造方法实例,最终通过反射完成 View 的创建,至此如果设置了 LayoutInflater.Factory ,则其创建 View 的过程基本如上。

从上文的分析我们知道当加载布局文件时会先看有没有设置 LayoutInflater.Factory,如果已经设置了则会由具体的 LayoutInflater.Factory 的规则去创建 View,否则就直接去使用反射去创建 View,所以可以自定义 LayoutInflater.Factory 来按照自己的规则去创建 View,如下:

// 第一种方式
@Override
protected void onCreate(Bundle savedInstanceState) {
    LayoutInflater layoutInflater =  getLayoutInflater();
    //设置LayoutInflater.Factory,必须在super.onCreate之前设置
    layoutInflater.setFactory(new LayoutInflater.Factory() {
        @Override
        public View onCreateView(String name, Context context, AttributeSet attrs) {
            // 将TextView替换成Button返回
            if (name.equals("TextView")){
                Button button = new Button(MainActivity.this);
                button.setText("我被替换成了Button");
                return button;
            }
            return null;
        }
    });
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

通过上述代码,当在加载布局文件解析 View 的时候,所有的 TextView 都会被替换成 Button,其他的 View 不也会自动转换为 AppCompatXxx 系列的 View,这样就使得当自行设置 LayoutInflater.Factory 会之后其他 View 会失去新特性的支持,对应 Log 内容如下:

I/AppCompatDelegate: The Activity's LayoutInflater already has a Factory installed so we can not install AppCompat's

那么如何保证能够继续使用新特性,又能够实现 View 的替换呢,通过前面分析我们知道系统组件的替换调用是 AppCompatDelegateImpl 的 createView 方法,而这个方法又是 public 的,所以只要能够在自定义之后继续调用 AppCompatDelegateImpl 的 createView 方法就能够保证其他 View 不被影响,如下:


// 第一种方式
LayoutInflaterCompat.setFactory2(layoutInflater, new LayoutInflater.Factory2() {
    @Override
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {

        if (name.equals("TextView")){
            Button button = new Button(MainActivity.this);
            button.setText("我被替换成了Button");
            return button;
        }

        AppCompatDelegate compatDelegate = getDelegate();
        View view = compatDelegate.createView(parent,name,context,attrs);
        return view;
    }

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        return onCreateView(null,name,context,attrs);
    }
});

下面分别是默认布局以及上述两种不同替换方式的布局视图结构,如下图所示:

此外,可以使用 LayoutInflater.Factory 来全局替换字体、换肤等功能进行延伸,关于 LayoutInflater.Factory 的源码解析就到此为止。