LayoutInflater 實例化獲取方法
1、一般我們獲取 LayoutInflater 對象都是通過 LayoutInflater 的 from 方法
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;
}
內部封裝了 getSystemService 方法,
2、我們也可以直接通過
LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
來獲取
3、Activity 也提供了 getLayoutInflater 方法,內部是調用的 Window 類的 getLayoutInflater 方法,歸根到底還是通過 getSystemService 來獲取。
LayoutInflater 的 View inflate(…) 方法族剖析
得到 LayoutInflater 對象之后我們就是傳遞 xml 然后解析得到 View
inflate 的重載方法有四個:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root)
public View inflate(XmlPullParser parser, @Nullable ViewGroup root)
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
根據第一個參數的區別,上面四個方法可以分為兩組,第一組傳入的參數是 int 類型的資源文件 ID,第二組傳入的是一個XmlPullParser 對象,而其實傳入布局 ID 后,也是被解析成了 XmlPullParser 對象,然后調用參數為 XmlPullParser 的重載方法:
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) + ")");
}
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
因為 layout 文件也是資源文件的一種,所以可以用Resources 的 getLayout 方法獲取,返回的就是 XmlpullParser 對象。
兩個參數的方法內部會調用三個參數的方法:
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;
View result = root;
try {
// Look for the root node.
int type;
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("**************************");
}
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 {
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// Create layout params that match root, if supplied
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
if (DEBUG) {
System.out.println("-----> start inflating children");
}
// Inflate all children under temp against its context.
rInflateChildren(parser, temp, attrs, true);
if (DEBUG) {
System.out.println("-----> done inflating children");
}
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// Decide whether to return the root that was passed in or the
// top view found in xml.
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
InflateException ex = new InflateException(e.getMessage());
ex.initCause(e);
throw ex;
} catch (Exception e) {
InflateException ex = new InflateException(
parser.getPositionDescription()
+ ": " + e.getMessage());
ex.initCause(e);
throw ex;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
}
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
return result;
}
前面部分是從 XmlPullParser 中解析屬性,然后判斷布局文件的根標簽是不是 merge,如果是 merge 的話,第二個參數不能為 null,并且第三個參數必須為 true。因為 merge 只能作為 xml 文件的根元素,在 View 樹中必須加載在其它 ViewGroup 里。
接下來判斷第二個參數 root 是否為 null,如果 root 不為 null,根據從 xml 文件中解析出來的 AttributeSet 中的 layout_width 和 layout_height 屬性生成 LayoutParams,如果第三個參數 attachToRoot 為 true,那么把解析出來的 View 根據生成的 LayoutParams 添加到 root 上,最后返回 root;如果為 false,那么只是把 LayoutParams 設置給解析出來的 View,并返回 View。
如果 root 為 null,那么直接返回解析出來的 View。
兩個參數的 inflate 方法中第三個參數的值是取決于第二個參數的,如果 root == null,那么 attachToRoot 默認為 false,反之 attachToRoot 默認為 true。
總結一下就是:
- inflate(xmlId,null) 等價于 inflate(xmlld,null,false),只創建 temp 的 View 并直接返回 temp,不能正確處理我們設置的寬和高;
- inflate(xmlId,root) 等價于 inflate(xmlId,root,true),創建 View,執行 root.addView(temp,params),返回 root,能正確處理我們設置的寬和高;
- inflate(xmlId,null,true) ,只創建 temp 的 View 并直接返回temp,不能正確處理我們設置的寬和高;
- inflate(xmlId,root,false),創建 View,執行 temp.setLayoutParams(params),返回 temp,能正確處理我們設置的寬和高;
簡單說就是 root 不為 null,會生成 LayoutParams,xml 文件中設置的寬高有效,如果這時候 attchToRoot 為true,把解析出來的 View 添加到 root 上面返回 root
View 也有 inflate 方法,其實也是封裝了生成 LayoutInfalter 調用 inflate 方法:
public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}
在 inflate 方法里面的細節并沒有作深入探討。
1.解析 XML 的根標簽。
2.如果是 merge,調用 rInflate 進行解析。它會把 merge 所有子 view 添加到根標簽中。
3.如果是普通標簽,調用 createViewFromTag 進行解析。
4.調用 rInflate 解析 temp 根元素下的子 view。并添加到 temp 中。