今天的主題是LayoutInflate是怎樣獲取布局并將其添加到父控件中去的,閑話不多說直接切入正題绎晃。
一、LayoutInflate的創(chuàng)建
一般我們添加布局時調(diào)用的方法有這么幾種:
1帖旨、View.inflate(parent.getContext(), R.layout.item_layout, null);
2箕昭、LayoutInflater.from(context).inflate(R.layout.item_layout, parent);
3、LayoutInflater.from(context).inflate(R.layout.item_layout, parent解阅,false);
4落竹、getLayoutInflater().inflate(R.layout.item_layout, parent);
5、getLayoutInflater().inflate(R.layout.item_layout, parent货抄,false);
那么上面這些方法又有哪些區(qū)別呢述召,帶著在這個疑問我們來閱讀源碼吧。
首先是View.inflate(parent.getContext(), R.layout.item_layout, null);
public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}
View.inflate(parent.getContext(), R.layout.item_layout, null);
方法最終會調(diào)用LayoutInflater.from(context)
方法來獲得LayoutInflater對象蟹地。那我們來看看LayoutInflater.from(context);
中做了哪些處理
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;
}
這里我們看到LayoutInflater最終是通過context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
來創(chuàng)建的积暖。我們再看看Activity中的getLayoutInflater()
對象是怎樣獲取LayoutInflater的
@NonNull
public LayoutInflater getLayoutInflater() {
return getWindow().getLayoutInflater();
}
@Override
public LayoutInflater getLayoutInflater() {
return mLayoutInflater;
}
public PhoneWindow(Context context) {
super(context);
mLayoutInflater = LayoutInflater.from(context);
}
通過上面的代碼我們可以很清晰的看到在Activity中調(diào)用getLayoutInflate()
方法會獲取PhoneWindow中的mLayoutInflater
對象而mLayoutInflater
對象實在PhoneWindow被創(chuàng)建的時候調(diào)用LayoutInflater.from(context);
來賦值的。
根據(jù)之前的代碼我們看到不論通過哪種形式的調(diào)用最終是通過context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
方法來創(chuàng)建LayoutInflater對象的怪与。
二夺刑、inflate()
我們經(jīng)常用的inflate方法主要是有兩個,一個是兩個參數(shù)的另外一個是三個參數(shù)的分别,我們分別來看看他們的區(qū)別吧
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
在上面源碼中我們看到兩個參數(shù)的inflate是調(diào)用三個參數(shù)的inflate方法遍愿,而第三個參數(shù)則傳入為父容器是否為空的布爾型參數(shù)下面我們通過源碼來分析一下這三個參數(shù)的作用
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();
}
}
這個方法很簡單就是獲取資源布局使用XmlResourceParser進行保存。并調(diào)用inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
方法耘斩。
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;
//獲取根節(jié)點并解析
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("**************************");
}
//這里判斷根節(jié)點是否為merge標簽如果是merge標簽并且沒有將資源文件往父容器添加的意圖就會跑出異常
//merge標簽是不能單獨存在的
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");
}
//遍歷子節(jié)點填充到父容器中沼填,直接返回父容器
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;
//如果存在父容器我們就根據(jù)attrs來設(shè)置View的參數(shù)
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.
//遍歷子節(jié)點將其填充到跟View中
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.
//如果滿足條件則將跟View添加到父容器中并返回父容器否則返回跟View
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) {
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;
}
}
這一段代碼就比較有意思了首先告訴我們merge標簽不能獨立于父容器存在的,其次告訴我們?nèi)绻粋魅敫溉萜鲃t不會給根View設(shè)置寬高屬性括授,也就是說我們在xml文件中設(shè)置的layout_width
和layout_height
都失去了作用坞笙。
我們再來看看rInflate:
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
final int depth = parser.getDepth();
int type;
//遍歷子節(jié)點并創(chuàng)建Viwe添加到父容器中
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
final String name = parser.getName();
if (TAG_REQUEST_FOCUS.equals(name)) {
parseRequestFocus(parser, parent);
} else if (TAG_TAG.equals(name)) {
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge /> must be the root element");
} else {
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflateChildren(parser, view, attrs, true);
viewGroup.addView(view, params);
}
}
if (finishInflate) {
parent.onFinishInflate();
}
}
這段代碼很簡單主要是遍歷子節(jié)點創(chuàng)建對應(yīng)的View添加到parent中岩饼,其中對幾個特殊的標簽做了處理。其中merge標簽不能在非根節(jié)點而include標簽不能在根節(jié)點薛夜。到此我們的代碼就分析完了籍茧。
總結(jié):
-
LayoutInflate的創(chuàng)建最終是通過
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
來創(chuàng)建的。 -
inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
方法的三個參數(shù)分別代表著子布局却邓,父容器硕糊,是否將子布局添加到父容器中。 - 如果父容器不為空并且
attachToRoot
的值為true的時候腊徙,inflate方法會將子布局添加到父容器中并返回父容器的對象简十,否則返回子布局的View對象。 - merge標簽只能在根節(jié)點使用而include標簽只能在非根節(jié)點使用撬腾。