相信隻要接觸過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>
add_view:
<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):
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiclRnblN0LclHdpZXYyd2LcBzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CX9kERPlXTU9UeBRUT41EVZZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39jN2ATMykTN2EzNwMDM3EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
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()方法有疑惑的同學!!