LayoutInflater Factory

LayoutInflater Factory 是什么?

setFactory(LayoutInflater.Factory factory)
setFactory2(LayoutInflater.Factory2 factory)
setFactory2是在SDK>11时候添加的,如果你是基于11以上的就使用setFactory2,否则就使用setFactory ,两者功能基本一致。当然你不想考虑兼容问题可以直接使用LayoutInflaterCompat.setFactory()。
其实就是一个接口,在系统填充view前会回调该接口,你可以去自定义布局的填充(有点类似于拦截器)。

LayoutInflater Factory 有什么用?

使用LayoutInflater Factory的这一特性可以做很多事:

提高view构建的效率

当我们使用自定义view时,需要在xml中使用完整类名,系统实际就是根据完整类名进行反射构建。我们可以自己new出view避免系统反射调用,提高效率。
替换默认view实现,改变或添加属性

替换系统控件

一键换肤解决方案

LayoutInflater Factory 怎么用?

public class TestLayoutFactory implements LayoutInflaterFactory {

    private static final String TAG = "TestLayoutFactory";

    @Override
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
        Log.d(TAG, "name = " + name);
        int n = attrs.getAttributeCount();
        for (int i = 0; i < n; i++)
        {
            Log.d(TAG, attrs.getAttributeName(i) + " , " + attrs.getAttributeValue(i));
        }

        return null;
    }

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    // 注意需在调用super.onCreate(savedInstanceState);之前设置
    LayoutInflaterCompat.setFactory(getLayoutInflater(), new TestLayoutFactory());
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test_layout_factory);
}

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout  android:id="@+id/activity_test_layout_factory" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.licheng.testapp.layoutfactory.TestLayoutFactoryActivity">

    <TextView  android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/test" android:textSize="16sp" android:padding="10dp" android:textColor="@android:color/white" android:background="@android:color/black" android:layout_gravity="center"/>

</FrameLayout>

在xml中使用完全类名。我们看下系统是如何构建我们自定义view的,一般的流程:inflate()->createViewFromTag()->CreateView()

我们先看看createViewFromTag()部分重要代码:

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

这里我们可以看到,根据name是否包含“.”来判断是否是自定义view,如果是自定义view就会调用CreateView()

public final View createView(String name, String prefix, AttributeSet attrs)
        throws ClassNotFoundException, InflateException { Constructor<? extends View> constructor = sConstructorMap.get(name); 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) { // 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); }
            }
            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;

        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;

    } catch (NoSuchMethodException e) { // 省略代码... }
}

我们根据以上代码可以知道系统根据标签name反射构建我们的自定义view,我们使用LayoutInflater Factory就可以自己去构建view :
我们可以不用在xml中写完整的类名,只要匹配到name我们就可以直接new出自定义view,避免系统反射调用,提高view创建速度。

替换默认View的实现

@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {

    if (TextUtils.equals("TextView", name)) {
        return new GoTextView(context,attrs);
    }

    return null;
}

其实兼容包也是这么做的,我们可以点开support library 的AppCompatActivity

protected void onCreate(@Nullable Bundle savedInstanceState) {
    final AppCompatDelegate delegate = getDelegate();
    delegate.installViewFactory();
    delegate.onCreate(savedInstanceState);
    // 省略代码....
    super.onCreate(savedInstanceState);
}

AppCompatActivity大部分功能是交给AppCompatDelegate去实现的,在onCreate中我们可以看到是调用了installViewFactory()

@Override
public void installViewFactory() {
    LayoutInflater layoutInflater = LayoutInflater.from(mContext);
    if (layoutInflater.getFactory() == null) {
        LayoutInflaterCompat.setFactory(layoutInflater, this);
    } else {
        if (!(LayoutInflaterCompat.getFactory(layoutInflater)
                instanceof AppCompatDelegateImplV9)) {
            Log.i(TAG, "The Activity's LayoutInflater already has a Factory installed"
                    + " so we can not install AppCompat's");
        }
    }
}

其实就是设置了一个Factory,我们看下设置的Factory的具体实现:

public 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) {
        // We then apply the theme on the context, if specified
        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 = new AppCompatTextView(context, attrs);
            break;
        case "ImageView":
            view = new AppCompatImageView(context, attrs);
            break;
        case "Button":
            view = new AppCompatButton(context, attrs);
            break;
        case "EditText":
            view = new AppCompatEditText(context, attrs);
            break;
        case "Spinner":
            view = new AppCompatSpinner(context, attrs);
            break;
        case "ImageButton":
            view = new AppCompatImageButton(context, attrs);
            break;
        case "CheckBox":
            view = new AppCompatCheckBox(context, attrs);
            break;
        case "RadioButton":
            view = new AppCompatRadioButton(context, attrs);
            break;
        case "CheckedTextView":
            view = new AppCompatCheckedTextView(context, attrs);
            break;
        case "AutoCompleteTextView":
            view = new AppCompatAutoCompleteTextView(context, attrs);
            break;
        case "MultiAutoCompleteTextView":
            view = new AppCompatMultiAutoCompleteTextView(context, attrs);
            break;
        case "RatingBar":
            view = new AppCompatRatingBar(context, attrs);
            break;
        case "SeekBar":
            view = new AppCompatSeekBar(context, attrs);
            break;
    }

    if (view == null && originalContext != context) {
        // If the original context does not equal our themed context, then we need to manually
        // inflate it using the name so that android:theme takes effect.
        view = createViewFromTag(context, name, attrs);
    }

    if (view != null) {
        // If we have created a view, check it's android:onClick
        checkOnClickListener(view, attrs);
    }

    return view;
}

从代码中可以一目了然的看出来,所有继承AppCompactActivity的Activity中都会将系统的 xxxView 替换为support library中的 AppCompatxxx,这就实现了新增功能与向下兼容。

LayoutInflater Factory 使用中遇到的问题

LayoutInflater Factoty有一个限制,只能被设置一次。如果被多次设置会抛出异常

/** * Attach a custom Factory interface for creating views while using * this LayoutInflater. This must not be null, and can only be set once; * after setting, you can not change the factory. * * @see LayoutInflater#setFactory(android.view.LayoutInflater.Factory) */
public static void setFactory(LayoutInflater inflater, LayoutInflaterFactory factory) {
    IMPL.setFactory(inflater, factory);
}

这个限制就会导致一个问题,我们在继承AppCompactActivity后设置自己的Factory会导致AppCompactActivity的Factory无效,无法使用最新的特性,那该怎么办的呢?

有以下几种解决方案:

在Activity的onCreateView()回调中实现我们自己的逻辑

使用layoutInflater.cloneInContext(context);克隆一个layoutInflater,再在这个克隆的里面setFactory

在我们的Factory中先调用AppCompatDelegate的createView()在进行我们的逻辑

我们来分别介绍一下:

在Activity的onCreateView()回调中实现我们自己的逻辑

Activity其实已经实现了Factory接口,并把实现通过接口回调的方式交给用户自己去做了,所以我们只需重载onCreateView()

我们看AppCompatDelegate中的代码,会先调用Activity的OnCreateView,如果返回不为null则自己进行构建。

/** * From {@link android.support.v4.view.LayoutInflaterFactory} */
@Override
public final View onCreateView(View parent, String name,
        Context context, AttributeSet attrs) {
    // First let the Activity's Factory try and inflate the view
    final View view = callActivityOnCreateView(parent, name, context, attrs);
    if (view != null) {
        return view;
    }

    // If the Factory didn't handle it, let our createView() method try
    return createView(parent, name, context, attrs);
}

所以我们可以在Activity的onCreateView中进行“拦截”,Activity的代码就是重载onCreateView:

public class TestLayoutFactoryActivity extends AppCompatActivity {

    private static final String TAG = "TestLayoutFactoryActivi";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 注意需在调用super.onCreate(savedInstanceState);之前设置
        //LayoutInflaterCompat.setFactory(getLayoutInflater(), new TestLayoutFactory());
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_layout_factory);
    }

    @Override
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
        if (TextUtils.equals("TextView", name)) {
            return new GoTextView(context, attrs);
        }
        // return null 交给系统去构建view
        return null;
    }
}

使用layoutInflater.cloneInContext(context);

layoutInflater提供api是cloneInContext(context);可以克隆一个layoutInflater

LayoutInflater newLayoutInlflater = getLayoutInflater().cloneInContext(context);
LayoutInflaterCompat.setFactory(newLayoutInlflater,new TestLayoutFactory());

这种方式不是很方便,需要在使用中将默认的LayoutInflater替换为我们新的LayoutInflater,但是也是一种思路。

在Factory中先调用AppCompatDelegate的createView()

好在AppCompatDelegate的createView()是public的,所以我们可以先执行自己的逻辑再交给delegate去实现:

public class TestLayoutFactory implements LayoutInflaterFactory {

    private AppCompatDelegate appCompatDelegate;

    private static final String TAG = "TestLayoutFactory";

    public TestLayoutFactory(AppCompatDelegate appCompatDelegate) {
        this.appCompatDelegate = appCompatDelegate;
    }

    @Override
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
        View result = null;

        // 实现我们自己的逻辑
        if (TextUtils.equals("TextView", name)) {
            result =  new GoTextView(context,attrs);
        }

        if (result == null) {
            // 使用 AppCompat 获取view
            result = appCompatDelegate.createView(parent, name, context, attrs);
        }
        return result;
    }

LayoutInflater Factory这一特性很强大,能做的远不止上面那些事。比如大部分“一键换肤”都是使用了这一特性来实现的。

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

推荐阅读更多精彩内容