
大家對LayoutInflater一定不陌生侧巨,它主要用于加載布局,在Fragment的onCreateView方法奢驯、ListView Adapter的getView方法等許多地方都可以見到它的身影适掰。今天主要聊聊LayoutInflater的用法以及加載布局的工作原理。
出處: Allen's Zone
作者: Allen Feng
什么是LayoutInflater
LayoutInflater是一個用于將xml布局文件加載為View或者ViewGroup對象的工具塑煎,我們可以稱之為布局加載器沫换。
用法
獲取LayoutInflater
首先要注意LayoutInflater本身是一個抽象類,我們不可以直接通過new
的方式去獲得它的實例最铁,通常有下面三種方式:
第一種:
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
第二種:
LayoutInflater inflater = LayoutInflater.from(context);
第三種:
在Activity內(nèi)部調(diào)用getLayoutInflater()方法
看看后面兩種方法的實現(xiàn):
public static LayoutInflater from(Context context) {
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null) {
throw new AssertionError("LayoutInflater not found.");
}
return LayoutInflater;
}
在Activity內(nèi)部調(diào)用getLayoutInflater方法其實調(diào)用的是PhoneWindow的mLayoutInflater:
public PhoneWindow(Context context) {
super(context);
mLayoutInflater = LayoutInflater.from(context);
}
所以讯赏,這幾個方法實際上殊途同歸,都是通過調(diào)用Context的getSystemService方法去獲取冷尉。獲取到的是PhoneLayoutInflater
這個實現(xiàn)類漱挎,具體的獲取過程就不在這里展開分析了。
public class Policy implements IPolicy {
...
public LayoutInflater makeNewLayoutInflater(Context context) {
return new PhoneLayoutInflater(context);
}
}
加載布局
我們用一個簡單的例子雀哨,介紹下LayoutInflater的用法:
這個例子的目標是在屏幕上展示一個按鈕识樱,點擊按鈕時,會通過LayoutInflater把一個橙色背景的TextView以
match_parent
的形式加載到一塊寬高為300dp的RelativeLayout中震束。
首先創(chuàng)建兩個布局文件:
demo_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:background="#ff750c"
android:text="Hello , world !" />
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="點擊加載" />
<RelativeLayout
android:id="@+id/root"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity {
RelativeLayout rootView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rootView = (RelativeLayout) findViewById(R.id.root);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
inflateView();
}
});
}
private void inflateView() {
View insideView = LayoutInflater.from(MainActivity.this).inflate(R.layout.demo_layout, null);
rootView.addView(insideView);
}
}
編譯運行怜庸,點擊點擊加載
按鈕,結果如下:

可以看到垢村,我們成功把demo_layout.xml對應布局中的TextView加載進來了割疾。
但遺憾的是,加載進來的TextView寬高并不是我們期望的300x300大小╮(╯▽╰)╭嘉栓。
那么問題來了:
- 為什么我們在布局文件中給TextView設置的寬高屬性失效了呢宏榕?
- LayoutInflater又是如何把xml解析加載成為View的呢?

而且侵佃,inflate有多個不同的重載方法:
inflate(int resource, ViewGroup root)
inflate(int resource, ViewGroup root, boolean attachToRoot)
inflate(XmlPullParser parser, ViewGroup root)
inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)
上面的例子只是使用了第一個方法麻昼,并且root的傳參還是null。
這些方法又有什么不同的地方呢馋辈?
我們從源碼入手抚芦,去尋找這兩個問題的答案。
源碼解析
上文有提到,我們獲取的LayoutInflater實例其實是PhoneLayoutInflater叉抡,但PhoneLayoutInflater并沒有重寫inflate的幾個方法尔崔,所以我們的分析還是在LayoutInflater這個類展開。
首先比對下這幾個重載方法:
public View inflate(int resource, ViewGroup root) {
// root不為空時褥民,attachToRoot默認為true
return inflate(resource, root, root != null);
}
public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
XmlResourceParser parser = getContext().getResources().getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
public View inflate(XmlPullParser parser, ViewGroup root) {
// root不為空時季春,attachToRoot默認為true
return inflate(parser, root, root != null);
}
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
...
}
原來,前三個方法最終調(diào)用的都是:
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
...
}
而且消返,root不為空時载弄,attachToRoot默認為true。布局id會被通過調(diào)用getLayout
方法生成一個XmlResourceParser
對象撵颊。
Android中布局文件都是使用xml編寫的侦锯,所以解析過程自然涉及xml的解析。常用的xml解析方式有DOM秦驯,SAX和PULL三種方式尺碰。DOM不適合xml文檔較大,內(nèi)存較小的場景译隘,所以不適用于手機這樣內(nèi)存有限的移動設備上亲桥。SAX和PULL類似,都具有解析速度快固耘,占用內(nèi)存少的優(yōu)點题篷,而相對之下,PULL的操作方式更為簡單易用厅目,所以番枚,Android系統(tǒng)內(nèi)部在解析各種xml時都用的是PULL解析器。
這里解析布局xml文件時使用的就是Android系統(tǒng)提供的PULL方式损敷。
我們繼續(xù)分析inflate方法葫笼。
inflate方法
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
final AttributeSet attrs = Xml.asAttributeSet(parser);
// 首先注意result初值為root
View result = root;
try {
// 嘗試找到布局文件的根節(jié)點
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
...
// 獲取當前節(jié)點名稱,如merge拗馒,RelativeLayout等
final String name = parser.getName();
...
// 處理merge節(jié)點
if (TAG_MERGE.equals(name)) {
// merge必須依附在一個根View上
if (root == null || !attachToRoot) {
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
rInflate(parser, root, attrs, false);
} else {
View temp;
// 根據(jù)當前信息生成一個View
temp = createViewFromTag(root, name, attrs);
...
ViewGroup.LayoutParams params = null;
if (root != null) {
// 如果指定了root參數(shù)的話路星,根據(jù)節(jié)點的布局參數(shù)生成合適的LayoutParams
params = root.generateLayoutParams(attrs);
// 若指定了attachToRoot為false,會將生成的布局參數(shù)應用于上一步生成的View
if (!attachToRoot) {
temp.setLayoutParams(params);
}
}
// 由上至下诱桂,遞歸加載xml內(nèi)View洋丐,并添加到temp里
rInflate(parser, temp, attrs, true);
// 如果root不為空且指定了attachToRoot為true時,會將temp作為子View添加到root中
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// 如果指定的root為空挥等,或者attachToRoot為false的時候友绝,返回的是加載出來的View,
// 否則返回root
if (root == null || !attachToRoot) {
result = temp;
}
}
} ... // 異常處理
return result;
}
}
首先定義布局根View這一個概念肝劲,注意與root并不是同一個東西:
- root是我們傳進來的第二個參數(shù)
- 布局根View則是傳遞進來的布局文件的根節(jié)點所對應的View
這個方法主要有下面幾個步驟:
- 首先查找根節(jié)點迁客,如果整個xml文件解析完畢也沒看到根節(jié)點郭宝,會拋出異常;
- 如果查找到的根節(jié)點名稱是merge標簽哲泊,會調(diào)用rInflate方法繼續(xù)解析布局剩蟀,最終返回root催蝗;
- 如果是其他標簽(View切威、TextView等),會調(diào)用createViewFromTag生成布局根View丙号,并調(diào)用rInflate遞歸解析余下的子View先朦,添加至布局根View中,最后視root和attachToRoot參數(shù)的情況最終返回view或者root犬缨。
從這里我們可以理清root和attachToRoot參數(shù)的關系了:
root != null喳魏, attachToRoot == true:
傳進來的布局會被加載成為一個View并作為子View添加到root中,最終返回root怀薛;
而且這個布局根節(jié)點的android:layout_參數(shù)會被解析用來設置View的大小刺彩。root == null, attachToRoot無用:
當root為空時枝恋,attachToRoot是什么都沒有意義创倔,此時傳進來的布局會被加載成為一個View并直接返回;
布局根View的android:layout_xxx屬性會被忽略焚碌。root != null畦攘, attachToRoot == false:
傳進來的布局會被加載成為一個View并直接返回。
布局根View的android:layout_xxx屬性會被解析成LayoutParams并保留十电。(root只用來參與生成布局根View的LayoutParams)
現(xiàn)在可以解答文章開始留下的疑問了:
為何在布局文件中給TextView設置的android:layout屬性失效了?
回到例子中的代碼知押,我們加載布局的代碼是:
View insideView = LayoutInflater.from(MainActivity.this).inflate(R.layout.demo_layout, null);
rootView.addView(insideView);
即root傳參為空,與上面第2種情況對應鹃骂,所以此時布局根View的android:layout_xx屬性都被忽略了台盯。也就是相當于并沒有給TextView設置寬高,所以只能按默認的TextView大小顯示了畏线。
稍微改變下代碼:
LayoutInflater.from(MainActivity.this).inflate(R.layout.demo_layout, rootView);
注意這段代碼等同于:
LayoutInflater.from(MainActivity.this).inflate(R.layout.demo_layout, rootView, true);
inflate方法在root不為空時爷恳,默認會將attachToRoot置為true。
這時等同于我們上面的情況1象踊,由于此時infalte會將加載出來的View自動添加到root中温亲,我們要把rootView.addView(insideView)
一句移除,否則會遇到這樣的報錯:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:4454)
at android.view.ViewGroup.addView(ViewGroup.java:4295)
at android.view.ViewGroup.addView(ViewGroup.java:4235)
at android.view.ViewGroup.addView(ViewGroup.java:4208)
再來運行看看:

終于達到我們想要的效果了杯矩!這也驗證了上面的第一個結論栈虚。
順便再用這個例子拓展一下,驗證我們的情況3史隆,即root != null魂务, attachToRoot == false
時的情況:
View insideView = LayoutInflater.from(MainActivity.this).inflate(R.layout.demo_layout, rootView, false);
rootView.addView(insideView);
結果是一樣的,圖就不貼了,即root != null粘姜, attachToRoot == false
時鬓照,root只是用來參與布局根View的大小、位置設置的孤紧。
好了豺裆,關于這兩個參數(shù)的疑問的解答就告一段落了,我們接著回到代碼号显,尋找另一個問題的答案臭猜。
繼續(xù)跟進rInflate和createViewFromTag方法。
rInflate方法
void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs,
boolean finishInflate) throws XmlPullParserException, IOException {
...
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
...
final String name = parser.getName();
// 解析“requestFocus”標簽押蚤,讓父View調(diào)用requestFocus()獲取焦點
if (TAG_REQUEST_FOCUS.equals(name)) {
...
} else if (TAG_INCLUDE.equals(name)) {
...
} else if (TAG_MERGE.equals(name)) {
...
} else if (TAG_1995.equals(name)) {
...
} else {
// 調(diào)用createViewFromTag生成一個View
final View view = createViewFromTag(parent, name, attrs);
// 逐層遞歸調(diào)用rInflate蔑歌,解析view嵌套的子View
rInflate(parser, view, attrs, true);
// 將解析生成子View添加到上一層View中
viewGroup.addView(view, params);
}
}
// 內(nèi)層子View被解析出來后,將調(diào)用其父View的“onFinishInflate()”回調(diào)
if (finishInflate) parent.onFinishInflate();
}
首先是幾個特殊標簽的處理揽碘,如requestFocus
次屠、include
等,為了把握住主要脈絡雳刺,我們不做展開劫灶,直接看最后一個else的內(nèi)容。
原來煞烫,rInflate主要是調(diào)用了createViewFromTag生成當前解析到的View節(jié)點浑此,并遞歸調(diào)用rInflate逐層生成子View,添加到各自的上層View節(jié)點中滞详。
當某個節(jié)點下面的所有子節(jié)點View解析生成完成后凛俱,才會調(diào)起onFinishInflate回調(diào)。
所以createViewFromTag才是真正生成View的地方啊料饥。
createViewFromTag方法
View createViewFromTag(View parent, String name, AttributeSet attrs) {
...
try {
View view;
if (mFactory2 != null) view = mFactory2.onCreateView(parent, name, mContext, attrs);
else if (mFactory != null) view = mFactory.onCreateView(name, mContext, attrs);
else view = null;
if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, mContext, attrs);
}
// 三個Factory都不存在調(diào)用LayoutInflater自己的onCreateView或者createView
//
// 如果View標簽中沒有"."蒲犬,則代表是系統(tǒng)的widget,則調(diào)用onCreateView岸啡,
// 這個方法會通過"createView"方法創(chuàng)建View
// 不過前綴字段會自動補"android.view."前綴原叮。
if (view == null) {
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
}
return view;
} catch (InflateException e) {
...
} ...
}
public interface Factory {
public View onCreateView(String name, Context context, AttributeSet attrs);
}
首先會依次調(diào)用mFactory2、mFactory和mPrivateFactory三者之一的onCreateView方法去創(chuàng)建一個View巡蘸。
如果這幾個Factory都為null奋隶,會調(diào)用LayoutInflater自己的onCreateView或者createView來實例化View。
自定義Factory一個十分有用的使用場景就是實現(xiàn)應用換膚悦荒,有興趣的讀者可以參考我開源的Android-Skin-Loader中的具體細節(jié)唯欣。
通常情況下,自定義工廠mFactory2搬味、mFactory和私有工廠mPrivateFactory是空的境氢,當Activity繼承自AppCompatActivity時蟀拷,才會存在自定義Factory。
所以萍聊,生成View的重任就落在了onCreateView和createView身上问芬。
onCreateView調(diào)用的其實是createView,即View的節(jié)點名稱沒有.
時寿桨,將自動補上android.view.
前綴(即完整類名):
protected View onCreateView(String name, AttributeSet attrs)
throws ClassNotFoundException {
return createView(name, "android.view.", attrs);
}
繼續(xù)關注的createView實現(xiàn)此衅。
createView方法
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
Constructor<? extends View> constructor = sConstructorMap.get(name);
Class<? extends View> clazz = null;
try {
if (constructor == null) {
// 緩存中不存在某View的構造方法,先new出來放緩存中
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
...
constructor = clazz.getConstructor(mConstructorSignature);
sConstructorMap.put(name, constructor);
} else {
...
}
Object[] args = mConstructorArgs;
args[1] = attrs;
return constructor.newInstance(args);
} catch (NoSuchMethodException e) {
...
}
}
這就是最后一步了牛隅,十分容易理解:
通過傳進來的全類名炕柔,調(diào)用newInstance
來創(chuàng)建一個這個類的實例并返回酌泰,返回的這個實例就是我們需要的View了媒佣。
結合上面的遞歸解析過程,每個層級的節(jié)點都會被生成一個個的View陵刹,并根據(jù)View的層級關系add到對應的直接父View(上層節(jié)點)中默伍,最終返回一個包含了所有解析好的子View的布局根View。
至此衰琐,通過xml來加載View的整個原理就分析完成了也糊。
總結
最后,我們再次回顧下上面的分析結果:
inflate方法的參數(shù)關系
root != null羡宙, attachToRoot == true
傳進來的布局會被加載成為一個View并作為子View添加到root中狸剃,最終返回root;
而且這個布局根節(jié)點的android:layout_xxx參數(shù)會被解析用來設置View的大泄啡取钞馁;root == null, attachToRoot無意義
當root為空時匿刮,attachToRoot無論是什么都沒有意義僧凰。此時傳進來的布局會被加載成為一個View并直接返回;
布局根View的android:layout_xxx
屬性會被忽略熟丸,即android:layout_xx屬性只有依附在某個ViewGroup中才能生效训措;root != null, attachToRoot == false
傳進來的布局會被加載成為一個View并直接返回光羞。
布局根View的android:layout_xxx
屬性會被解析成LayoutParams并設置在View上绩鸣,此時root只用于設置布局根View的大小和位置。
加載xml布局的原理
其實就是從根節(jié)點開始纱兑,遞歸解析xml的每個節(jié)點呀闻,每一步遞歸的過程是:通過節(jié)點名稱(全類名),使用ClassLoader創(chuàng)建對應類的實例萍启,也就是View总珠,然后屏鳍,將這個View添加到它的上層節(jié)點(父View)。并同時會解析對應xml節(jié)點的屬性作為View的屬性局服。每個層級的節(jié)點都會被生成一個個的View钓瞭,并根據(jù)View的層級關系add到對應的直接父View(上層節(jié)點)中,最終返回一個包含了所有解析好的子View的布局根View淫奔。
出處: Allen's Zone
作者: Allen Feng