LayoutInflater Factory

LayoutInflater Factory 是什么菩掏?

setFactory(LayoutInflater.Factory factory)
setFactory2(LayoutInflater.Factory2 factory)
setFactory2是在SDK>11時(shí)候添加的刀诬,如果你是基于11以上的就使用setFactory2,否則就使用setFactory ,兩者功能基本一致稍味。當(dāng)然你不想考慮兼容問題可以直接使用LayoutInflaterCompat.setFactory()隧熙。
其實(shí)就是一個(gè)接口,在系統(tǒng)填充view前會(huì)回調(diào)該接口睬魂,你可以去自定義布局的填充(有點(diǎn)類似于攔截器)终吼。

LayoutInflater Factory 有什么用?

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

提高view構(gòu)建的效率

當(dāng)我們使用自定義view時(shí)汉买,需要在xml中使用完整類名衔峰,系統(tǒng)實(shí)際就是根據(jù)完整類名進(jìn)行反射構(gòu)建。我們可以自己new出view避免系統(tǒng)反射調(diào)用蛙粘,提高效率垫卤。
替換默認(rèn)view實(shí)現(xiàn),改變或添加屬性

替換系統(tǒng)控件

一鍵換膚解決方案

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) {
    // 注意需在調(diào)用super.onCreate(savedInstanceState);之前設(shè)置
    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中使用完全類名穴肘。我們看下系統(tǒng)是如何構(gòu)建我們自定義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;
    }
}

這里我們可以看到舔痕,根據(jù)name是否包含“.”來判斷是否是自定義view评抚,如果是自定義view就會(huì)調(diào)用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) { // 省略代碼... }
}

我們根據(jù)以上代碼可以知道系統(tǒng)根據(jù)標(biāo)簽name反射構(gòu)建我們的自定義view,我們使用LayoutInflater Factory就可以自己去構(gòu)建view :
我們可以不用在xml中寫完整的類名伯复,只要匹配到name我們就可以直接new出自定義view慨代,避免系統(tǒng)反射調(diào)用,提高view創(chuàng)建速度啸如。

替換默認(rèn)View的實(shí)現(xiàn)

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

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

    return null;
}

其實(shí)兼容包也是這么做的侍匙,我們可以點(diǎn)開support library 的AppCompatActivity

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

AppCompatActivity大部分功能是交給AppCompatDelegate去實(shí)現(xiàn)的,在onCreate中我們可以看到是調(diào)用了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");
        }
    }
}

其實(shí)就是設(shè)置了一個(gè)Factory叮雳,我們看下設(shè)置的Factory的具體實(shí)現(xiàn):

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中都會(huì)將系統(tǒng)的 xxxView 替換為support library中的 AppCompatxxx妇汗,這就實(shí)現(xiàn)了新增功能與向下兼容。

LayoutInflater Factory 使用中遇到的問題

LayoutInflater Factoty有一個(gè)限制说莫,只能被設(shè)置一次杨箭。如果被多次設(shè)置會(huì)拋出異常

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

這個(gè)限制就會(huì)導(dǎo)致一個(gè)問題,我們?cè)诶^承AppCompactActivity后設(shè)置自己的Factory會(huì)導(dǎo)致AppCompactActivity的Factory無效储狭,無法使用最新的特性互婿,那該怎么辦的呢?

有以下幾種解決方案:

在Activity的onCreateView()回調(diào)中實(shí)現(xiàn)我們自己的邏輯

使用layoutInflater.cloneInContext(context);克隆一個(gè)layoutInflater晶密,再在這個(gè)克隆的里面setFactory

在我們的Factory中先調(diào)用AppCompatDelegate的createView()在進(jìn)行我們的邏輯

我們來分別介紹一下:

在Activity的onCreateView()回調(diào)中實(shí)現(xiàn)我們自己的邏輯

Activity其實(shí)已經(jīng)實(shí)現(xiàn)了Factory接口擒悬,并把實(shí)現(xiàn)通過接口回調(diào)的方式交給用戶自己去做了,所以我們只需重載onCreateView()

我們看AppCompatDelegate中的代碼稻艰,會(huì)先調(diào)用Activity的OnCreateView懂牧,如果返回不為null則自己進(jìn)行構(gòu)建。

/** * 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中進(jìn)行“攔截”尊勿,Activity的代碼就是重載onCreateView:

public class TestLayoutFactoryActivity extends AppCompatActivity {

    private static final String TAG = "TestLayoutFactoryActivi";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 注意需在調(diào)用super.onCreate(savedInstanceState);之前設(shè)置
        //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 交給系統(tǒng)去構(gòu)建view
        return null;
    }
}

使用layoutInflater.cloneInContext(context);

layoutInflater提供api是cloneInContext(context)僧凤;可以克隆一個(gè)layoutInflater

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

這種方式不是很方便,需要在使用中將默認(rèn)的LayoutInflater替換為我們新的LayoutInflater元扔,但是也是一種思路躯保。

在Factory中先調(diào)用AppCompatDelegate的createView()

好在AppCompatDelegate的createView()是public的,所以我們可以先執(zhí)行自己的邏輯再交給delegate去實(shí)現(xiàn):

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;

        // 實(shí)現(xiàn)我們自己的邏輯
        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這一特性很強(qiáng)大澎语,能做的遠(yuǎn)不止上面那些事途事。比如大部分“一鍵換膚”都是使用了這一特性來實(shí)現(xiàn)的。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末擅羞,一起剝皮案震驚了整個(gè)濱河市尸变,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌减俏,老刑警劉巖召烂,帶你破解...
    沈念sama閱讀 221,273評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異娃承,居然都是意外死亡奏夫,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,349評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門历筝,熙熙樓的掌柜王于貴愁眉苦臉地迎上來酗昼,“玉大人,你說我怎么就攤上這事梳猪÷橄鳎” “怎么了?”我有些...
    開封第一講書人閱讀 167,709評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長碟婆。 經(jīng)常有香客問我,道長惕稻,這世上最難降的妖魔是什么竖共? 我笑而不...
    開封第一講書人閱讀 59,520評(píng)論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮俺祠,結(jié)果婚禮上公给,老公的妹妹穿的比我還像新娘。我一直安慰自己蜘渣,他們只是感情好淌铐,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,515評(píng)論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著蔫缸,像睡著了一般腿准。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上拾碌,一...
    開封第一講書人閱讀 52,158評(píng)論 1 308
  • 那天吐葱,我揣著相機(jī)與錄音,去河邊找鬼校翔。 笑死弟跑,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的防症。 我是一名探鬼主播孟辑,決...
    沈念sama閱讀 40,755評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼蔫敲!你這毒婦竟也來了饲嗽?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,660評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤燕偶,失蹤者是張志新(化名)和其女友劉穎喝噪,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體指么,經(jīng)...
    沈念sama閱讀 46,203評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡酝惧,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,287評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了伯诬。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片晚唇。...
    茶點(diǎn)故事閱讀 40,427評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖盗似,靈堂內(nèi)的尸體忽然破棺而出哩陕,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 36,122評(píng)論 5 349
  • 正文 年R本政府宣布悍及,位于F島的核電站闽瓢,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏心赶。R本人自食惡果不足惜扣讼,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,801評(píng)論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望缨叫。 院中可真熱鬧椭符,春花似錦、人聲如沸耻姥。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,272評(píng)論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽琐簇。三九已至蒸健,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間鸽嫂,已是汗流浹背纵装。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評(píng)論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留据某,地道東北人橡娄。 一個(gè)月前我還...
    沈念sama閱讀 48,808評(píng)論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像癣籽,于是被迫代替她去往敵國和親挽唉。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,440評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容