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這一特性很強大,能做的遠不止上面那些事。比如大部分“一鍵換膚”都是使用了這一特性來實現的。