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)的。