用法
獲取LayoutInflater
首先要注意LayoutInflater本身是一個(gè)抽象類,我們不可以直接通過new的方式去獲得它的實(shí)例,通常有下面三種方式:
第一種:
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
第二種:
LayoutInflater inflater = LayoutInflater.from(context);
第三種:
在Activity內(nèi)部調(diào)用getLayoutInflater()方法
看看后面兩種方法的實(shí)現(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方法其實(shí)調(diào)用的是PhoneWindow的mLayoutInflater:
public PhoneWindow(Context context) {
super(context);
mLayoutInflater = LayoutInflater.from(context);
}
所以,這幾個(gè)方法實(shí)際上殊途同歸,都是通過調(diào)用Context的getSystemService方法去獲取。獲取到的是PhoneLayoutInflater這個(gè)實(shí)現(xiàn)類,具體的獲取過程就不在這里展開分析了。
public class Policy implements IPolicy {
...
public LayoutInflater makeNewLayoutInflater(Context context) {
return new PhoneLayoutInflater(context);
}
}
加載布局
我們用一個(gè)簡單的例子,介紹下LayoutInflater的用法:
這個(gè)例子的目標(biāo)是在屏幕上展示一個(gè)按鈕,點(diǎn)擊按鈕時(shí),會通過LayoutInflater把一個(gè)橙色背景的TextView以match_parent的形式加載到一塊寬高為300dp的RelativeLayout中。
首先創(chuàng)建兩個(gè)布局文件:
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="點(diǎn)擊加載" />
<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);
}
}
編譯運(yùn)行,點(diǎn)擊點(diǎn)擊加載按鈕,結(jié)果如下:
點(diǎn)擊按鈕后
可以看到,我們成功把demo_layout.xml對應(yīng)布局中的TextView加載進(jìn)來了。
但遺憾的是,加載進(jìn)來的TextView寬高并不是我們期望的300x300大小╮(╯▽╰)╭。
那么問題來了:
為什么我們在布局文件中給TextView設(shè)置的寬高屬性失效了呢?
LayoutInflater又是如何把xml解析加載成為View的呢?
而且,inflate有多個(gè)不同的重載方法:
inflate(int resource, ViewGroup root)
inflate(int resource, ViewGroup root, boolean attachToRoot)
inflate(XmlPullParser parser, ViewGroup root)
inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)
上面的例子只是使用了第一個(gè)方法,并且root的傳參還是null。
這些方法又有什么不同的地方呢?
我們從源碼入手,去尋找這兩個(gè)問題的答案。
源碼解析
上文有提到,我們獲取的LayoutInflater實(shí)例其實(shí)是PhoneLayoutInflater,但PhoneLayoutInflater并沒有重寫inflate的幾個(gè)方法,所以我們的分析還是在LayoutInflater這個(gè)類展開。
首先比對下這幾個(gè)重載方法:
public View inflate(int resource, ViewGroup root) {
// root不為空時(shí),attachToRoot默認(rèn)為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不為空時(shí),attachToRoot默認(rèn)為true
return inflate(parser, root, root != null);
}
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
...
}
原來,前三個(gè)方法最終調(diào)用的都是:
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
...
}
而且,root不為空時(shí),attachToRoot默認(rèn)為true。布局id會被通過調(diào)用getLayout方法生成一個(gè)XmlResourceParser對象。
Android中布局文件都是使用xml編寫的,所以解析過程自然涉及xml的解析。常用的xml解析方式有DOM,SAX和PULL三種方式。DOM不適合xml文檔較大,內(nèi)存較小的場景,所以不適用于手機(jī)這樣內(nèi)存有限的移動(dòng)設(shè)備上。SAX和PULL類似,都具有解析速度快,占用內(nèi)存少的優(yōu)點(diǎn),而相對之下,PULL的操作方式更為簡單易用,所以,Android系統(tǒng)內(nèi)部在解析各種xml時(shí)都用的是PULL解析器。
這里解析布局xml文件時(shí)使用的就是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é)點(diǎn)
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
...
// 獲取當(dāng)前節(jié)點(diǎn)名稱,如merge,RelativeLayout等
final String name = parser.getName();
...
// 處理merge節(jié)點(diǎn)
if (TAG_MERGE.equals(name)) {
// merge必須依附在一個(gè)根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ù)當(dāng)前信息生成一個(gè)View
temp = createViewFromTag(root, name, attrs);
...
ViewGroup.LayoutParams params = null;
if (root != null) {
// 如果指定了root參數(shù)的話,根據(jù)節(jié)點(diǎn)的布局參數(shù)生成合適的LayoutParams
params = root.generateLayoutParams(attrs);
// 若指定了attachToRoot為false,會將生成的布局參數(shù)應(yīng)用于上一步生成的View
if (!attachToRoot) {
temp.setLayoutParams(params);
}
}
// 由上至下,遞歸加載xml內(nèi)View,并添加到temp里
rInflate(parser, temp, attrs, true);
// 如果root不為空且指定了attachToRoot為true時(shí),會將temp作為子View添加到root中
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// 如果指定的root為空,或者attachToRoot為false的時(shí)候,返回的是加載出來的View,
// 否則返回root
if (root == null || !attachToRoot) {
result = temp;
}
}
} ... // 異常處理
return result;
}
}
首先定義布局根View這一個(gè)概念,注意與root并不是同一個(gè)東西:
root是我們傳進(jìn)來的第二個(gè)參數(shù)
布局根View則是傳遞進(jìn)來的布局文件的根節(jié)點(diǎn)所對應(yīng)的View
這個(gè)方法主要有下面幾個(gè)步驟:
首先查找根節(jié)點(diǎn),如果整個(gè)xml文件解析完畢也沒看到根節(jié)點(diǎn),會拋出異常;
如果查找到的根節(jié)點(diǎn)名稱是merge標(biāo)簽,會調(diào)用rInflate方法繼續(xù)解析布局,最終返回root;
如果是其他標(biāo)簽(View、TextView等),會調(diào)用createViewFromTag生成布局根View,并調(diào)用rInflate遞歸解析余下的子View,添加至布局根View中,最后視r(shí)oot和attachToRoot參數(shù)的情況最終返回view或者root。
從這里我們可以理清root和attachToRoot參數(shù)的關(guān)系了:
root != null, attachToRoot == true:
傳進(jìn)來的布局會被加載成為一個(gè)View并作為子View添加到root中,最終返回root;
而且這個(gè)布局根節(jié)點(diǎn)的android:layout_參數(shù)會被解析用來設(shè)置View的大小。
root == null, attachToRoot無用:
當(dāng)root為空時(shí),attachToRoot是什么都沒有意義,此時(shí)傳進(jìn)來的布局會被加載成為一個(gè)View并直接返回;
布局根View的android:layout_xxx屬性會被忽略。
root != null, attachToRoot == false:
傳進(jìn)來的布局會被加載成為一個(gè)View并直接返回。
布局根View的android:layout_xxx屬性會被解析成LayoutParams并保留。(root只用來參與生成布局根View的LayoutParams)
現(xiàn)在可以解答文章開始留下的疑問了:
為何在布局文件中給TextView設(shè)置的android:layout屬性失效了?
回到例子中的代碼,我們加載布局的代碼是:
View insideView = LayoutInflater.from(MainActivity.this).inflate(R.layout.demo_layout, null);
rootView.addView(insideView);
即root傳參為空,與上面第2種情況對應(yīng),所以此時(shí)布局根View的android:layout_xx屬性都被忽略了。也就是相當(dāng)于并沒有給TextView設(shè)置寬高,所以只能按默認(rèn)的TextView大小顯示了。
稍微改變下代碼:
LayoutInflater.from(MainActivity.this).inflate(R.layout.demo_layout, rootView);
注意這段代碼等同于:
LayoutInflater.from(MainActivity.this).inflate(R.layout.demo_layout, rootView, true);
inflate方法在root不為空時(shí),默認(rèn)會將attachToRoot置為true。
這時(shí)等同于我們上面的情況1,由于此時(shí)infalte會將加載出來的View自動(dòng)添加到root中,我們要把rootView.addView(insideView)一句移除,否則會遇到這樣的報(bào)錯(cuò):
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)
再來運(yùn)行看看:
終于達(dá)到我們想要的效果了!這也驗(yàn)證了上面的第一個(gè)結(jié)論。
順便再用這個(gè)例子拓展一下,驗(yàn)證我們的情況3,即root != null, attachToRoot == false時(shí)的情況:
View insideView = LayoutInflater.from(MainActivity.this).inflate(R.layout.demo_layout, rootView, false);
rootView.addView(insideView);
結(jié)果是一樣的,圖就不貼了,即root != null, attachToRoot == false時(shí),root只是用來參與布局根View的大小、位置設(shè)置的。
好了,關(guān)于這兩個(gè)參數(shù)的疑問的解答就告一段落了,我們接著回到代碼,尋找另一個(gè)問題的答案。
繼續(xù)跟進(jìn)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”標(biāo)簽,讓父View調(diào)用requestFocus()獲取焦點(diǎn)
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生成一個(gè)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();
}
首先是幾個(gè)特殊標(biāo)簽的處理,如requestFocus、include等,為了把握住主要脈絡(luò),我們不做展開,直接看最后一個(gè)else的內(nèi)容。
原來,rInflate主要是調(diào)用了createViewFromTag生成當(dāng)前解析到的View節(jié)點(diǎn),并遞歸調(diào)用rInflate逐層生成子View,添加到各自的上層View節(jié)點(diǎn)中。
當(dāng)某個(gè)節(jié)點(diǎn)下面的所有子節(jié)點(diǎn)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);
}
// 三個(gè)Factory都不存在調(diào)用LayoutInflater自己的onCreateView或者createView
//
// 如果View標(biāo)簽中沒有".",則代表是系統(tǒng)的widget,則調(diào)用onCreateView,
// 這個(gè)方法會通過"createView"方法創(chuàng)建View
// 不過前綴字段會自動(dòng)補(bǔ)"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)建一個(gè)View。
如果這幾個(gè)Factory都為null,會調(diào)用LayoutInflater自己的onCreateView或者createView來實(shí)例化View。
自定義Factory一個(gè)十分有用的使用場景就是實(shí)現(xiàn)應(yīng)用換膚,有興趣的讀者可以參考我開源的Android-Skin-Loader中的具體細(xì)節(jié)。
通常情況下,自定義工廠mFactory2、mFactory和私有工廠mPrivateFactory是空的,當(dāng)Activity繼承自AppCompatActivity時(shí),才會存在自定義Factory。
所以,生成View的重任就落在了onCreateView和createView身上。
onCreateView調(diào)用的其實(shí)是createView,即View的節(jié)點(diǎn)名稱沒有.時(shí),將自動(dòng)補(bǔ)上android.view.前綴(即完整類名):
protected View onCreateView(String name, AttributeSet attrs)
throws ClassNotFoundException {
return createView(name, "android.view.", attrs);
}
繼續(xù)關(guān)注的createView實(shí)現(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的構(gòu)造方法,先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) {
...
}
}
這就是最后一步了,十分容易理解:
通過傳進(jìn)來的全類名,調(diào)用newInstance來創(chuàng)建一個(gè)這個(gè)類的實(shí)例并返回,返回的這個(gè)實(shí)例就是我們需要的View了。
結(jié)合上面的遞歸解析過程,每個(gè)層級的節(jié)點(diǎn)都會被生成一個(gè)個(gè)的View,并根據(jù)View的層級關(guān)系add到對應(yīng)的直接父View(上層節(jié)點(diǎn))中,最終返回一個(gè)包含了所有解析好的子View的布局根View。
至此,通過xml來加載View的整個(gè)原理就分析完成了。
總結(jié)
最后,我們再次回顧下上面的分析結(jié)果:
inflate方法的參數(shù)關(guān)系
root != null, attachToRoot == true
傳進(jìn)來的布局會被加載成為一個(gè)View并作為子View添加到root中,最終返回root;
而且這個(gè)布局根節(jié)點(diǎn)的android:layout_xxx參數(shù)會被解析用來設(shè)置View的大小;
root == null, attachToRoot無意義
當(dāng)root為空時(shí),attachToRoot無論是什么都沒有意義。此時(shí)傳進(jìn)來的布局會被加載成為一個(gè)View并直接返回;
布局根View的android:layout_xxx屬性會被忽略,即android:layout_xx屬性只有依附在某個(gè)ViewGroup中才能生效;
root != null, attachToRoot == false
傳進(jìn)來的布局會被加載成為一個(gè)View并直接返回。
布局根View的android:layout_xxx屬性會被解析成LayoutParams并設(shè)置在View上,此時(shí)root只用于設(shè)置布局根View的大小和位置。
加載xml布局的原理
其實(shí)就是從根節(jié)點(diǎn)開始,遞歸解析xml的每個(gè)節(jié)點(diǎn),每一步遞歸的過程是:通過節(jié)點(diǎn)名稱(全類名),使用ClassLoader創(chuàng)建對應(yīng)類的實(shí)例,也就是View,然后,將這個(gè)View添加到它的上層節(jié)點(diǎn)(父View)。并同時(shí)會解析對應(yīng)xml節(jié)點(diǎn)的屬性作為View的屬性。每個(gè)層級的節(jié)點(diǎn)都會被生成一個(gè)個(gè)的View,并根據(jù)View的層級關(guān)系add到對應(yīng)的直接父View(上層節(jié)點(diǎn))中,最終返回一個(gè)包含了所有解析好的子View的布局根View。