LayoutInflater中有兩個(gè)inflate方法:
- public View inflate( int resource, ViewGroup root)
- public View inflate(int resource, ViewGroup root, boolean attachToRoot)
測(cè)試
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
final LayoutInflater inflater = getLayoutInflater();
//A
final View view1 = inflater.inflate(R.layout.activity_main, null);
//B
final View view2 = inflater.inflate(R.layout.activity_main, (ViewGroup) findViewById(android.R.id.content),false);
//C。并且會(huì)顯示在界面上
final View view3 = inflater.inflate(R.layout.activity_main, (ViewGroup) findViewById(android.R.id.content),true);
// 參數(shù)為Null
Log.d(TAG, "onCreate() view1: " + view1 +"layoutparam = "+view1.getLayoutParams());
// 有參數(shù)FrameLayout$LayoutParams
Log.d(TAG, "onCreate() view2: " + view2 +"layoutparam = "+view2.getLayoutParams());
//有參數(shù)LinearLayout$LayoutParams
Log.d(TAG, "onCreate() view3: " + view3 +"layoutparam = "+view3.getLayoutParams());
}
分析ABC
三個(gè)方法最后都會(huì)調(diào)用下面這個(gè):
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
...跳過一堆代碼...
View result = root;
// Temp 就是我們的xml布局
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
//如果是上面的A調(diào)用,則不會(huì)創(chuàng)建layout params
if (root != null) {
//B和C 根據(jù)root創(chuàng)建layout params
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
//B 第三個(gè)參數(shù)attachToRoot為 false,則會(huì)設(shè)置layout params
temp.setLayoutParams(params);
}
}
//C 如果設(shè)置了root并且第三個(gè)參數(shù)為true.則使用params把temp添加 的root上去
if (root != null && attachToRoot) {
root.addView(temp, params);
}
//A 如果root沒設(shè)置并且第三參數(shù)為false
//則直接返回temp
if (root == null || !attachToRoot) {
result = temp;
}
/*
A:返回的是temp
B:返回的是root,temp設(shè)置了params,但沒有添加 到root上
C:返回的是root并且會(huì)把布局添加到root上
*/
return result;
}
對(duì)定義view的影響
onMeasure()方法都會(huì)根據(jù)測(cè)量模式做不同處理
MeasureSpec.EXACTLY == LayoutParams. MATCH_PARENT或設(shè)置的一個(gè)精確值
MeasureSpec.AT_MOST == LayoutParams. WRAP_CONTENT
可以知曉測(cè)量時(shí)依賴于LayoutParams种柑。而inflate(resId,null)是不會(huì)設(shè)置LayoutParams的核芽。
在listview中出現(xiàn)item設(shè)置的寬高沒有被處理的時(shí)候可以檢查一下是否正確調(diào)用了inflate方法