LayoutInflater
開頭先附一段LayoutInflater類的注釋簡介
/**
* Instantiates a layout XML file into its corresponding {@link android.view.View}
* objects. It is never used directly. Instead, use
* {@link android.app.Activity#getLayoutInflater()} or
* {@link Context#getSystemService} to retrieve a standard LayoutInflater instance
* that is already hooked up to the current context and correctly configured
* for the device you are running on.
*
* To create a new LayoutInflater with an additional {@link Factory} for your
* own views, you can use {@link #cloneInContext} to clone an existing
* ViewFactory, and then call {@link #setFactory} on it to include your
* Factory.
*
* For performance reasons, view inflation relies heavily on pre-processing of
* XML files that is done at build time. Therefore, it is not currently possible
* to use LayoutInflater with an XmlPullParser over a plain XML file at runtime;
* it only works with an XmlPullParser returned from a compiled resource
* (R.<em>something</em> file.)
*/
這是LayoutInflater開頭的一段介紹,我們能看到幾個重要的信息:
- LayoutInfalter的作用是把XML轉(zhuǎn)化成對應(yīng)的View對象灭翔,需要用
Activity#getLayoutInflater()
或者getSystemService
獲取谚中,會綁定當(dāng)前的Context - 如果需要使用自定義的
Factory
查看替換加載信息,需要用cloneInContext去克隆一個ViewFactory
囱嫩,然后調(diào)用setFactory
設(shè)置自定義的Factory - 性能原因,inflate會在build階段進行,無法用來加載一個外部文本XML文件破喻,只能加載R.xxx.xxx這種處理好的資源文件。
//LayoutInflater.java
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
//root是否為null來決定attachToRoot是否為true盟榴。
return inflate(resource, root, root != null);
}
public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {
return inflate(parser, root, root != null);
}
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
...
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
//三個inflate方法最終都會調(diào)用到下面這個三個參數(shù)的inflate方法曹质。
/**
* parser XML節(jié)點包含了View的層級描述
* root 需要attached到的根目錄,如果attachToRoot為true則root必須不為null。
* attachToRoot 加載的層級是否需要attach到rootView羽德,
* return attachToRoot為true几莽,就返回root,反之false就返回加載的XML文件的根節(jié)點View宅静。
*/
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
View result = root;
try {
// Look for the root node.
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription() + ": No start tag found!");
}
final String name = parser.getName();
...
if (TAG_MERGE.equals(name)) {
if (root == null || !attachToRoot) {
throw new InflateException("<merge /> can be used only with a valid " + "ViewGroup root and attachToRoot=true");
}
rInflate(parser, root, inflaterContext, attrs, false);
} else {
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
// Create layout params that match root, if supplied
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
rInflateChildren(parser, temp, attrs, true);
...
// We are supposed to attach all the views we found (int temp) to root. Do that now.
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// Decide whether to return the root that was passed in or the top view found in xml.
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
...
}
return result;
}
}
inflate方法使用XmlPullParser解析XML文件章蚣,并根據(jù)得到的標(biāo)簽名執(zhí)行不同的邏輯:
1、首先如果是merge
標(biāo)簽姨夹,會走rInflate方法纤垂,方法前面帶r
的說明是recurse
遞歸方法
2、如果不是merge
標(biāo)簽磷账,執(zhí)行createViewFromTag
峭沦,根據(jù)傳入的name
和attrs
獲取到name對應(yīng)的rootView并且添加到root里面。
針對merge
標(biāo)簽逃糟,如果是merge
標(biāo)簽必須有root并且必須attachToRoot==true
吼鱼,否則直接拋異常,所以我們得知merge必須作為root標(biāo)簽使用履磨,并且不能用在子標(biāo)簽中①蛉抓,rInflate
方法中也會針對merge
標(biāo)簽進行檢查,保證merge
標(biāo)簽不會出現(xiàn)在子標(biāo)簽中剃诅,后面會有介紹巷送。
檢查通過則調(diào)用rInflate(parser, root, inflaterContext, attrs, false)
方法,遞歸遍歷root的層級矛辕,解析加載childrenView掛載到parentView下面笑跛,rinflate詳細解析可以看rinflate。
如果不是merge標(biāo)簽則調(diào)用createViewFromTag(root, name, inflaterContext, attrs)
聊品,這個方法的作用是加載名字為name的view
飞蹂,根據(jù)name反射方式創(chuàng)建對應(yīng)的View,根據(jù)傳入的attrs
構(gòu)造Params設(shè)置給View翻屈,返回創(chuàng)建好的View陈哑。
當(dāng)然這只是創(chuàng)建了一個View,需要再調(diào)用rInflateChildren(parser, temp, attrs, true)
伸眶,這個方法也是一個遞歸方法惊窖,它的作用是根據(jù)傳入的parser包含的層級,加載此層級的子View并掛載到temp
下面厘贼。
createViewFromTag
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
// Apply a theme wrapper, if allowed and one is specified.
// 如果傳入的attr中包含theme屬性界酒,則使用此attr中的theme。
if (!ignoreThemeAttr) {
final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
final int themeResId = ta.getResourceId(0, 0);
if (themeResId != 0) {
context = new ContextThemeWrapper(context, themeResId);
}
ta.recycle();
}
if (name.equals(TAG_1995)) {
// Let's party like it's 1995!
return new BlinkLayout(context, attrs);
}
try {
View view;
if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, context, attrs);
} else if (mFactory != null) {
view = mFactory.onCreateView(name, context, attrs);
} else {
view = null;
}
if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, context, attrs);
}
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;
}
}
return view;
} catch (Exception e) {
...
}
}
先看當(dāng)前標(biāo)簽的attr屬性里面是否設(shè)置了theme嘴秸,如果設(shè)置了就用當(dāng)前標(biāo)簽的theme屬性毁欣,綁定到context上面庇谆。
這里很有意思的是特殊判斷了一個TAG_1995
,也就是blink
凭疮,一個將包裹的內(nèi)容每隔500ms
顯示隱藏的一個標(biāo)簽饭耳,怎么看都像個彩蛋~
然后調(diào)用mFactory2
的onCreateView
,如果沒有設(shè)置mFactory2
就嘗試mFactory
,否則調(diào)用mPrivateFactory
,mFactory2和mFactory后面再說哭尝,這里先往后走哥攘。
如果還是沒有加載到view,先判斷name材鹦,看名字里是不是有.
逝淹,如果沒有就表明是Android原生的View,最終都會調(diào)用到createView
方法桶唐,onCreateView
最終會調(diào)用到createView(name, "android.view.", attrs);
栅葡,會在View名字天面添加"android.view."前綴。
下面是默認(rèn)的createView的實現(xiàn):
@Nullable
public final View createView(@NonNull Context viewContext, @NonNull String name,
@Nullable String prefix, @Nullable AttributeSet attrs)
throws ClassNotFoundException, InflateException {
Objects.requireNonNull(viewContext);
Objects.requireNonNull(name);
Constructor<? extends View> constructor = sConstructorMap.get(name);
if (constructor != null && !verifyClassLoader(constructor)) {
constructor = null;
sConstructorMap.remove(name);
}
Class<? extends View> clazz = null;
try {
if (constructor == null) {
// Class not found in the cache, see if it's real, and try to add it
clazz = Class.forName(prefix != null ? (prefix + name) : name, false,
mContext.getClassLoader()).asSubclass(View.class);
if (mFilter != null && clazz != null) {
boolean allowed = mFilter.onLoadClass(clazz);
if (!allowed) {
failNotAllowed(name, prefix, viewContext, 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 = Class.forName(prefix != null ? (prefix + name) : name, false,
mContext.getClassLoader()).asSubclass(View.class);
boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
mFilterMap.put(name, allowed);
if (!allowed) {
failNotAllowed(name, prefix, viewContext, attrs);
}
} else if (allowedState.equals(Boolean.FALSE)) {
failNotAllowed(name, prefix, viewContext, attrs);
}
}
}
Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = viewContext;
Object[] args = mConstructorArgs;
args[1] = attrs;
try {
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;
} finally {
mConstructorArgs[0] = lastContext;
}
} catch (Exception e) {
...
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
這個方法可以看到View是怎么創(chuàng)建出來的尤泽,用類的全限定名拿到class信息欣簇,有一個sConstructorMap
緩存類的constructor
,如果能拿到有效的構(gòu)造器就不再重復(fù)創(chuàng)建來提升效率坯约,如果沒有緩存的構(gòu)造器熊咽,就反射得到構(gòu)造器并添加到sConstructorMap
中以便后面使用。這里有個mFilter
來提供自定義選項闹丐,用戶可以自定義哪些類不允許構(gòu)造横殴。
拿到構(gòu)造器之后,實際上newInstance
是調(diào)用了兩View
個參數(shù)的構(gòu)造方法卿拴。第一個參數(shù)是Context
衫仑,第二個參數(shù)是attrs
,這樣我們就得到了需要加載的View堕花。
這里可以結(jié)合LayoutInflater.Factory2
一起來看文狱,Activity實際上是實現(xiàn)了LayoutInflater.Factory2
接口的:
//Activity.java
public View onCreateView(@NonNull String name, @NonNull Context context,
@NonNull AttributeSet attrs) {
return null;
}
所以我們可以直接在Activity里面重寫onCreateView
方法,這樣就可以根據(jù)View的名字來實現(xiàn)我們的一些操作缘挽,比如換膚的操作瞄崇,比如定義一個名字來表示某種自定義View『韭可以看這樣一個用法:
<PlaceHolder
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="include LinearLayout"
android:textColor="#fff"
android:textSize="15sp" />
然后我們在重寫的onCreateView
里面判斷name:
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
if ("PlaceHolder".equals(name)) {
return new TextView(this, attrs);
}
return super.onCreateView(name, context, attrs);
}
這樣其實就不拘泥于名字可以自己創(chuàng)建對應(yīng)的View杠袱,這樣其實可以用在多個module依賴的時候,如果在moduleA中得不到moduleB的某個自定義View窝稿,可以使用一個這樣的方式來在moudleA中暫時的用來做一個占位標(biāo)記,在moduleB中做一個判斷凿掂。
同樣的伴榔,通過上面的代碼我們知道LayoutInflater是通過反射拿到構(gòu)造方法來創(chuàng)建View的纹蝴,那眾所周知反射是有性能損耗的,那么我們可以在onCreateView
方法中判斷名字直接new出來踪少,當(dāng)然也可以跟AppcompatActivity里面做的一樣塘安,做一些兼容的操作來替換成不同版本的View:
public final View createView(View parent, final String name, @NonNull Context context,
View view = null;
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;
...
}
...
return view;
}
還沒有展開說rinflate,篇幅限制援奢,放到另外一篇文章中去分析兼犯,rinflate源碼分析。
流程圖如下:
總結(jié):
- LayoutInfalter的作用是把XML轉(zhuǎn)化成對應(yīng)的View對象集漾,需要用
Activity#getLayoutInflater()
或者getSystemService
獲取 - 加載時先判斷是否是merge標(biāo)簽切黔,merge標(biāo)簽走遞歸方法rinflate,否則走createViewFromTag
- createViewFromTag作用是根據(jù)xml標(biāo)簽的名字去加載對應(yīng)的View具篇,使用的是反射的方法
- LayoutInflater.Factory2是設(shè)計出來靈活構(gòu)造View的接口纬霞,可以用來實現(xiàn)換膚或者替換View的功能,同時也是AppcompatActivity用來做兼容和版本替換的接口