用法
獲取LayoutInflater
首先要注意LayoutInflater本身是一個抽象類,我們不可以直接通過new的方式去獲得它的實例,通常有下面三種方式:
第一種:
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
第二種:
LayoutInflater inflater = LayoutInflater.from(context);
第三種:
在Activity內部調用getLayoutInflater()方法
看看后面兩種方法的實現:
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內部調用getLayoutInflater方法其實調用的是PhoneWindow的mLayoutInflater:
public PhoneWindow(Context context) {
super(context);
mLayoutInflater = LayoutInflater.from(context);
}
所以,這幾個方法實際上殊途同歸,都是通過調用Context的getSystemService方法去獲取。獲取到的是PhoneLayoutInflater這個實現類,具體的獲取過程就不在這里展開分析了。
public class Policy implements IPolicy {
...
public LayoutInflater makeNewLayoutInflater(Context context) {
return new PhoneLayoutInflater(context);
}
}
加載布局
我們用一個簡單的例子,介紹下LayoutInflater的用法:
這個例子的目標是在屏幕上展示一個按鈕,點擊按鈕時,會通過LayoutInflater把一個橙色背景的TextView以match_parent的形式加載到一塊寬高為300dp的RelativeLayout中。
首先創建兩個布局文件:
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) {
...
}
原來,前三個方法最終調用的都是:
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
...
}
而且,root不為空時,attachToRoot默認為true。布局id會被通過調用getLayout方法生成一個XmlResourceParser對象。
Android中布局文件都是使用xml編寫的,所以解析過程自然涉及xml的解析。常用的xml解析方式有DOM,SAX和PULL三種方式。DOM不適合xml文檔較大,內存較小的場景,所以不適用于手機這樣內存有限的移動設備上。SAX和PULL類似,都具有解析速度快,占用內存少的優點,而相對之下,PULL的操作方式更為簡單易用,所以,Android系統內部在解析各種xml時都用的是PULL解析器。
這里解析布局xml文件時使用的就是Android系統提供的PULL方式。
我們繼續分析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 {
// 嘗試找到布局文件的根節點
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
...
// 獲取當前節點名稱,如merge,RelativeLayout等
final String name = parser.getName();
...
// 處理merge節點
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;
// 根據當前信息生成一個View
temp = createViewFromTag(root, name, attrs);
...
ViewGroup.LayoutParams params = null;
if (root != null) {
// 如果指定了root參數的話,根據節點的布局參數生成合適的LayoutParams
params = root.generateLayoutParams(attrs);
// 若指定了attachToRoot為false,會將生成的布局參數應用于上一步生成的View
if (!attachToRoot) {
temp.setLayoutParams(params);
}
}
// 由上至下,遞歸加載xml內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是我們傳進來的第二個參數
布局根View則是傳遞進來的布局文件的根節點所對應的View
這個方法主要有下面幾個步驟:
首先查找根節點,如果整個xml文件解析完畢也沒看到根節點,會拋出異常;
如果查找到的根節點名稱是merge標簽,會調用rInflate方法繼續解析布局,最終返回root;
如果是其他標簽(View、TextView等),會調用createViewFromTag生成布局根View,并調用rInflate遞歸解析余下的子View,添加至布局根View中,最后視root和attachToRoot參數的情況最終返回view或者root。
從這里我們可以理清root和attachToRoot參數的關系了:
root != null, attachToRoot == true:
傳進來的布局會被加載成為一個View并作為子View添加到root中,最終返回root;
而且這個布局根節點的android:layout_參數會被解析用來設置View的大小。
root == null, attachToRoot無用:
當root為空時,attachToRoot是什么都沒有意義,此時傳進來的布局會被加載成為一個View并直接返回;
布局根View的android:layout_xxx屬性會被忽略。
root != null, attachToRoot == false:
傳進來的布局會被加載成為一個View并直接返回。
布局根View的android:layout_xxx屬性會被解析成LayoutParams并保留。(root只用來參與生成布局根View的LayoutParams)
現在可以解答文章開始留下的疑問了:
為何在布局文件中給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的大小、位置設置的。
好了,關于這兩個參數的疑問的解答就告一段落了,我們接著回到代碼,尋找另一個問題的答案。
繼續跟進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調用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 {
// 調用createViewFromTag生成一個View
final View view = createViewFromTag(parent, name, attrs);
// 逐層遞歸調用rInflate,解析view嵌套的子View
rInflate(parser, view, attrs, true);
// 將解析生成子View添加到上一層View中
viewGroup.addView(view, params);
}
}
// 內層子View被解析出來后,將調用其父View的“onFinishInflate()”回調
if (finishInflate) parent.onFinishInflate();
}
首先是幾個特殊標簽的處理,如requestFocus、include等,為了把握住主要脈絡,我們不做展開,直接看最后一個else的內容。
原來,rInflate主要是調用了createViewFromTag生成當前解析到的View節點,并遞歸調用rInflate逐層生成子View,添加到各自的上層View節點中。
當某個節點下面的所有子節點View解析生成完成后,才會調起onFinishInflate回調。
所以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都不存在調用LayoutInflater自己的onCreateView或者createView
//
// 如果View標簽中沒有".",則代表是系統的widget,則調用onCreateView,
// 這個方法會通過"createView"方法創建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);
}
首先會依次調用mFactory2、mFactory和mPrivateFactory三者之一的onCreateView方法去創建一個View。
如果這幾個Factory都為null,會調用LayoutInflater自己的onCreateView或者createView來實例化View。
自定義Factory一個十分有用的使用場景就是實現應用換膚,有興趣的讀者可以參考我開源的Android-Skin-Loader中的具體細節。
通常情況下,自定義工廠mFactory2、mFactory和私有工廠mPrivateFactory是空的,當Activity繼承自AppCompatActivity時,才會存在自定義Factory。
所以,生成View的重任就落在了onCreateView和createView身上。
onCreateView調用的其實是createView,即View的節點名稱沒有.時,將自動補上android.view.前綴(即完整類名):
protected View onCreateView(String name, AttributeSet attrs)
throws ClassNotFoundException {
return createView(name, "android.view.", attrs);
}
繼續關注的createView實現。
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) {
...
}
}
這就是最后一步了,十分容易理解:
通過傳進來的全類名,調用newInstance來創建一個這個類的實例并返回,返回的這個實例就是我們需要的View了。
結合上面的遞歸解析過程,每個層級的節點都會被生成一個個的View,并根據View的層級關系add到對應的直接父View(上層節點)中,最終返回一個包含了所有解析好的子View的布局根View。
至此,通過xml來加載View的整個原理就分析完成了。
總結
最后,我們再次回顧下上面的分析結果:
inflate方法的參數關系
root != null, attachToRoot == true
傳進來的布局會被加載成為一個View并作為子View添加到root中,最終返回root;
而且這個布局根節點的android:layout_xxx參數會被解析用來設置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布局的原理
其實就是從根節點開始,遞歸解析xml的每個節點,每一步遞歸的過程是:通過節點名稱(全類名),使用ClassLoader創建對應類的實例,也就是View,然后,將這個View添加到它的上層節點(父View)。并同時會解析對應xml節點的屬性作為View的屬性。每個層級的節點都會被生成一個個的View,并根據View的層級關系add到對應的直接父View(上層節點)中,最終返回一個包含了所有解析好的子View的布局根View。