我們通常的使用
View view = View.inflate(this, R.layout.activity_handler, null);
//第一個方法調用第二個方法
view = LayoutInflater.from(this).inflate(R.layout.activity_handler,null);
//第二個方法調用第三個方法,我們從這看源碼
view = LayoutInflater.from(this).inflate(R.layout.activity_handler,null,false);
我們來看inflate方法
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
//這里調用了三個參數的方法,最后一個參數為root != null,所以最重要的是搞清楚root究竟是什么,root != null和= null的區別
return inflate(resource, 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) + ")");
}
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;
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.
//當root不為null,attachToRoot為true時,表示將resource指定的布局添加到root中
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;
}
}
這里我們分三種情況討論:
- 當root不為null,attachToRoot為true時
當root不為null,attachToRoot為true時,表示將resource指定的布局添加到root中,這里需要注意的是,當你這樣寫的時候
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.linearlayout, ll, true);
ll.addView(view);
}
系統會拋如下異常:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
相信我們肯定遇到過該異常,原因就是因為當第三個參數為true時,會自動將第一個參數所指定的View添加到第二個參數所指定的View中。即上面的inflate源碼中的:
if (root != null && attachToRoot) {
root.addView(temp, params);
}
- 當root不為null,attachToRoot為false時
當root不為null,attachToRoot為false時,此時沒有將第一個參數所指定的View添加到root中,但是將該view的LayoutParams設置給該view的根節點,源碼如下:
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);
}
}
- 當root為null時
當root為null時,不論attachToRoot為true還是為false,顯示效果都是一樣的。當root為null表示我不需要將第一個參數所指定的布局添加到root中,同時也表示沒有任將所指定布局的根節點設置布局參數。源碼如下:
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
if (root == null || !attachToRoot) {
//result 為返回的view
result = temp;
}
其他:
- 這里我們了解一下Activity的結構,Activity有一個頂級View叫做DecorView,DecorView中包含一個豎直方向的LinearLayout,LinearLayout由兩部分組成,第一部分是標題欄,第二部分是內容欄,內容欄是一個FrameLayout,我們在Activity中調用setContentView就是將View添加到這個FrameLayout中。這篇文章詳細分析了setContentView的源碼從setContentView源碼看起,看AppCompatActivity是如何用貍貓換太子的
- 當我們在RecyclerView.Adapter中使用如下代碼的時候,會發現item布局并沒有鋪滿RecyclerView,這下知道原因了吧
View view = View.inflate(this, R.layout.item_calendarview, null);