相信只要接觸過Android的同學都有用過LayoutInflater這個類,它的作用說起來很簡單,通過:
LayoutInflater.inflate(intresource,ViewGroup root, boolean attachToRoot)
將我們的佈局文件轉化成我們java類中的一個View,但這個inflate方法的參數也總讓人摸不着頭腦,resource很簡單,要轉化的佈局資源。root?恩.......那就是根佈局吧。attachToRoot?恩......那就是是否附屬在根佈局上。話說英文翻譯它們還是不難的,畢竟桌面右下角還有個“有道”呢。但是這翻譯出來後好像並沒什麼用,感覺還是不知道怎麼去用它們,root到底要傳什麼?到底要不要讓這個view附屬在根佈局上?接下來帶着這兩個參數的問題我們進入主題。
1、獲取LayoutInflater
我們獲取LayoutInflater一般有以下方法:
方法一:LayoutInflater.from(Context context);
方法二:(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
方法一源碼如下:
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;
}
可以看到方法一就是給方法二加了個非空保護。
2、使用LayoutInflater
首先看一個很簡單的demo,新建一個module,在主頁面通過LayoutInflate動態加入一個佈局。
activity_main:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"/>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="80dp"
android:background="#88FF00"
android:orientation="vertical">
<TextView
android:layout_width="100dp"
android:layout_height="60dp"
android:background="#00FFFF"
android:gravity="center"
android:text="ADD_VIEW"/>
</LinearLayout>
MainActivity代碼如下:
public class MainActivity extends AppCompatActivity {
private ViewGroup llContent;
private View addView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
llContent = (ViewGroup) findViewById(R.id.ll_content);
addView = LayoutInflater.from(this).inflate(R.layout.add_view, null);
// addView = LayoutInflater.from(this).inflate(R.layout.add_view, llContent);
// addView = LayoutInflater.from(this).inflate(R.layout.add_view, null, false);
// addView = LayoutInflater.from(this).inflate(R.layout.add_view, null, true);
// addView = LayoutInflater.from(this).inflate(R.layout.add_view, llContent, false);
// addView = LayoutInflater.from(this).inflate(R.layout.add_view, llContent, true);
llContent.addView(addView);
}
}
代碼再簡單不過了,第10行拿到MainActivity頂部佈局llContent,第11行通過LayoutInflater獲取到需要添加到MainAcitivity中的佈局addView,第17行將addView添加到llContent。註釋的部分是root和attachToRoot爲不同值時的情況。
3、分析LayoutInflater
我們進入inflate方法,看它到底是如何工作。
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
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();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}
//通過傳入的資源返回一個xmlPaser.
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final Context inflaterContext = mContext;
//初始化屬性
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
//默認將返回的result賦值爲傳入的root
View result = root;
try {
//首先解析資源根節點(下面都將傳入資源的頂層節點稱爲根節點,需與傳入的root區分)。
int type;
//如果不是start節點也不是end節點,則資源爲空
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 (DEBUG) {
System.out.println("**************************");
System.out.println("Creating root view: "
+ name);
System.out.println("**************************");
}
//判斷根節點是否爲merge(佈局優化時會使用到),如果爲merge,那麼傳入的root就不能爲null,
//且attachToRoot必須爲true,否組拋出異常。
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 {
//如果根節點不爲merge節點,這裏創建出根節點的View-->temp
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
//聲明根節點的params
ViewGroup.LayoutParams params = null;
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
//如果根節點不爲null,通過root初始化params。
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
//如果不附着在root上,則將params設置給temp
temp.setLayoutParams(params);
}
}
if (DEBUG) {
System.out.println("-----> start inflating children");
}
//開始解析子節點
rInflateChildren(parser, temp, attrs, true);
if (DEBUG) {
System.out.println("-----> done inflating children");
}
//如果root不爲空且附着在root上時,root直接add添加temp。
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// 如果root等於空或者不附着在root上時,直接將temp返回。
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
final InflateException ie = new InflateException(e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (Exception e) {
final InflateException ie = new InflateException(parser.getPositionDescription()
+ ": " + e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
return result;
}
}
inflate一共有4個重載方法,可以看出最終都進入了最後的inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)方法,所以直接說明一下最後的這個inflate方法。關鍵部分都已註釋,下面再來梳理一下。
4、結論
我們來看下上面代碼的幾個關鍵部分:
4.1、第35行,定義inflate方法返回的View,默認爲傳入的root。它在109行條件滿足時被重新複製,也就是當root爲空或者attachToRoot爲false時,它會被重新賦值爲傳入的資源的根節點對應的view(temp)。換種說法:當我們使用inflate方法傳入的root不爲空且attachToRoot爲true時,inflate最終會返回傳入的root,否則inflate方法會返回傳入資源的根節點對應的view。
4.2、第104行和109行其實爲兩個對立的if判斷(不能理解爲什麼不用else),第104行結合結論1有:當我們使用inflate方法傳入的root不爲空且attachToRoot爲true時,inflate最終會返回傳入的root,且該root已經add過傳入的資源佈局。
4.3、第74行初始化傳入資源的根view(temp)。第77行聲明temp的params。第79行當傳入的root不爲空,在第85行通過root爲params賦值,且只有當第86行temp不附着在root上時纔將params設置給temp(這裏可以解釋爲什麼我們有時通過inflate獲取到的view設置的大小不受控制)。
最後我們回過頭看看我們MainActivity中的幾種不同inflate方法到底會有怎麼樣的結果。
1、addView = LayoutInflater.from(this).inflate(R.layout.add_view, null):
add_view最外層大小並不是佈局中設置的大小,這裏剛好驗證了以上結論4.3點的root爲空的情況。
2、addView = LayoutInflater.from(this).inflate(R.layout.add_view,
llContent):
Caused by: 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:3940)
at android.view.ViewGroup.addView(ViewGroup.java:3790)
at android.view.ViewGroup.addView(ViewGroup.java:3731)
at android.view.ViewGroup.addView(ViewGroup.java:3704)
at com.minhao.myapplication.MainActivity.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:6084)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1117)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2472)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2586)
at android.app.ActivityThread.access$900(ActivityThread.java:163)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1462)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5566)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:962)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
這種情況下APP直接崩潰了,錯誤日誌如上,簡單的說就是你添加的view已經有了parent,不能重複添加。爲什麼會出現這種情況呢,通過第一個inflate方法可以看到,當值傳入root時,只要root不爲空,attachToRoot就爲true。結合以上結論4.2,這種情況下,root已將temp添加了,這時在MainActivity第17行不需要重複添加,去掉該行即可。
下面的addView = LayoutInflater.from(this).inflate(R.layout.add_view, llContent, true)同樣也是這種結果。
3、addView = LayoutInflater.from(this).inflate(R.layout.add_view, null, false)和
addView = LayoutInflater.from(this).inflate(R.layout.add_view, null, false),與1致。
4、addView = LayoutInflater.from(this).inflate(R.layout.add_view, llContent, false);
表現出了我們想要的效果,也證明了結論4.3點的正常情況。
到這裏LayoutInflater的初步解析就到這裏了,希望能幫助到對LayoutInflater.inflate()方法有疑惑的同學!!