在上一篇文章《Android LayoutInflater 源碼解析》中咱們說到 View 的 inflate 中有一個方法 createViewFromTag,會首先嚐試經過 Factory 來 CreateView。java
View view;
if (mFactory2 != null) {
// ① 有mFactory2,則調用mFactory2的onCreateView方法
view = mFactory2.onCreateView(parent, name, context, attrs);
} else if (mFactory != null) {
// ② 有mFactory,則調用mFactory的onCreateView方法
view = mFactory.onCreateView(name, context, attrs);
} else {
view = null;
}
複製代碼
正常狀況下這個Factory是空的,那何時不爲空,以及 LayoutInflater Factory 的具體用法,咱們今天就帶着這兩個問題來詳細學習下。android
備註:本文基於 Android 8.1.0。bash
LayoutInflater.Factory 中沒有說明,那咱們來看下它惟一方法的說明:微信
Hook you can supply that is called when inflating from a LayoutInflater. You can use this to customize the tag names available in your XML layout files.app
翻譯過來就是:經過 LayoutInflater 建立View時候的一個回調,能夠經過LayoutInflater.Factory來改造 XML 中存在的 tag。ide
咱們來看下這個惟一的方法:佈局
public abstract View onCreateView (String name, Context context, AttributeSet attrs)
複製代碼
那麼咱們就明白了,若是咱們設置了LayoutInflater Factory ,在LayoutInflater 的 createViewFromTag 方法中就會經過這個 Factory 的 onCreateView 方法來建立 View。學習
那怎麼理解上述引用的這個改造呢?舉個簡單的例子:好比你在 XML中 寫了一個 TextView標籤,而後在 onCreateView 這個回調裏 判斷若是 name 是 TextView 的話能夠變成一個Button,這樣的功能能夠實現例如批量更換某一個控件等的用途。例子以下:ui
佈局文件
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.liuzhaofutrue.teststart.MainActivity">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
複製代碼
接下來咱們在 Java 代碼中作修改:this
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
LayoutInflater.from(this).setFactory2(new LayoutInflater.Factory2() {
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
if(TextUtils.equals(name,"TextView")){
Button button = new Button(MainActivity.this);
button.setText("我替換了TextView");
button.setAllCaps(false);
return button;
}
return getDelegate().createView(parent, name, context, attrs);
}
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
return null;
}
});
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
複製代碼
能夠看到,原本在佈局文件中須要展現的是一個 TextView,可是如今卻被改形成了一個 Button。
備註:其實還有一個關係密切的類 LayoutInflater.Factory2 ,與 LayoutInflater.Factory 的區別是:
剛剛咱們說到,LayoutInflater.Factory2 是API 11 被加進來的,那麼 LayoutInflaterCompat 就是拿來作兼容的類。咱們來看下它最重要的兩個方法:
@Deprecated
public static void setFactory(
@NonNull LayoutInflater inflater, @NonNull LayoutInflaterFactory factory) {
IMPL.setFactory(inflater, factory);
}
public static void setFactory2(
@NonNull LayoutInflater inflater, @NonNull LayoutInflater.Factory2 factory) {
IMPL.setFactory2(inflater, factory);
}
複製代碼
能夠看到 setFactory 已經被標記爲過期,更建議使用 setFactory2 方法。
static final LayoutInflaterCompatBaseImpl IMPL;
static {
if (Build.VERSION.SDK_INT >= 21) {
IMPL = new LayoutInflaterCompatApi21Impl();
} else {
IMPL = new LayoutInflaterCompatBaseImpl();
}
}
@RequiresApi(21)
static class LayoutInflaterCompatApi21Impl extends LayoutInflaterCompatBaseImpl {
@SuppressWarnings("deprecation")
@Override
public void setFactory(LayoutInflater inflater, LayoutInflaterFactory factory) {
inflater.setFactory2(factory != null ? new Factory2Wrapper(factory) : null);
}
@Override
public void setFactory2(LayoutInflater inflater, LayoutInflater.Factory2 factory) {
inflater.setFactory2(factory);
}
}
複製代碼
這裏調用 setFactory 實際上仍是調用的 setFactory2 方法,同時將 LayoutInflaterFactory 包裹爲 Factory2Wrapper。
若是咱們將LayoutInflater.setFactory 挪到 super.onCreate 的後面能夠嗎? 程序居然報錯了,咱們看下Log:
Process: com.example.teststart, PID: 24132
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.teststart/com.example.teststart.MainActivity}: java.lang.IllegalStateException: A factory has already been set on this LayoutInflater
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2876)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2941)
Caused by: java.lang.IllegalStateException: A factory has already been set on this LayoutInflater
at android.view.LayoutInflater.setFactory2(LayoutInflater.java:317)
at com.example.teststart.MainActivity.onCreate(MainActivity.java:18)
at android.app.Activity.performCreate(Activity.java:6765)
複製代碼
說明是 LayoutInflater 已經被設置了一個 Factory,而咱們再設置的時候就會報錯。咱們跟蹤下 LayoutInflater.from(this).setFactory2 方法:
private boolean mFactorySet;
public void setFactory2(Factory2 factory) {
if (mFactorySet) {
throw new IllegalStateException("A factory has already been set on this LayoutInflater");
}
if (factory == null) {
throw new NullPointerException("Given factory can not be null");
}
mFactorySet = true;
if (mFactory == null) {
mFactory = mFactory2 = factory;
} else {
mFactory = mFactory2 = new FactoryMerger(factory, factory, mFactory, mFactory2);
}
}
複製代碼
能夠經過這個 mFactorySet 變量看出 setFactory2 方法只能被調用一次,重複設置則會拋出異常。那Factory2是被誰設置了呢?
咱們來看下 AppCompatActivity 的 onCreate 方法,
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
final AppCompatDelegate delegate = getDelegate();
delegate.installViewFactory();
delegate.onCreate(savedInstanceState);
if (delegate.applyDayNight() && mThemeId != 0) {
// If DayNight has been applied, we need to re-apply the theme for
// the changes to take effect. On API 23+, we should bypass
// setTheme(), which will no-op if the theme ID is identical to the
// current theme ID.
if (Build.VERSION.SDK_INT >= 23) {
onApplyThemeResource(getTheme(), mThemeId, false);
} else {
setTheme(mThemeId);
}
}
super.onCreate(savedInstanceState);
}
複製代碼
其中會調用 delegate.installViewFactory(); 最終會調用到 AppCompatDelegateImplV9 的 installViewFactory方法;
@Override
public void installViewFactory() {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
if (layoutInflater.getFactory() == null) {
LayoutInflaterCompat.setFactory2(layoutInflater, this);
} else {
if (!(layoutInflater.getFactory2() instanceof AppCompatDelegateImplV9)) {
Log.i(TAG, "The Activity's LayoutInflater already has a Factory installed"
+ " so we can not install AppCompat's");
}
}
}
複製代碼
能夠看到:
備註:聰明的小夥伴確定能想到使用反射來改變修改 LayoutInflater 中的 mFactorySet 爲false就能夠在 super.onCreate 以後再次設置 Factory了。
那麼爲何 AppCompatActivity 會自動設置一個 Factory呢?順着 AppCompatDelegateImplV9 的 installViewFactory方法繼續跟蹤,走到了 onCreateView 方法,它最終會調用到 AppCompatViewInflater 的 createView 方法。
public final View createView(View parent, final String name, @NonNull Context context,
@NonNull AttributeSet attrs, boolean inheritContext,
boolean readAndroidTheme, boolean readAppTheme, boolean wrapContext) {
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;
......
}
return view;
}
複製代碼
原來 AppCompatActivity 設置 Factory 是爲了將一些 widget 自動變成 兼容widget (例如將 TextView 變成 AppCompatTextView)以便於向下兼容新版本中的效果,在高版本中的一些 widget 新特性就是這樣在老版本中也能展現的。
那若是咱們設置了本身的 Factory 豈不是就避開了系統的兼容?其實系統的兼容咱們仍然能夠保存下來,由於系統是經過 AppCompatDelegate.onCreateView 方法來實現 widget 兼容的,那咱們就能夠在設置 Factory 的時候先調用 AppCompatDelegate.onCreateView 方法,再來作咱們的處理。
LayoutInflater.from(this).setFactory2(new LayoutInflater.Factory2() {
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
// 調用 AppCompatDelegate 的createView方法
getDelegate().createView(parent, name, context, attrs);
// 再來執行咱們的定製化操做
return null;
}
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
return null;
}
});
複製代碼
今日頭條各Android客戶端團隊招人火爆進行中,各個級別和應屆實習生都須要,業務增加快、日活高、挑戰大、待遇給力,各位大佬走過路過千萬不要錯過!
本科以上學歷、非頻繁跳槽(如兩年兩跳),歡迎加個人微信詳聊:KOBE8242011