LayoutInflater中有兩個inflate方法:
- public View inflate( int resource, ViewGroup root)
- public View inflate(int resource, ViewGroup root, boolean attachToRoot)
測試
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。并且會顯示在界面上
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
三個方法最后都會調(diào)用下面這個:
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)用,則不會創(chuàng)建layout params
if (root != null) {
//B和C 根據(jù)root創(chuàng)建layout params
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
//B 第三個參數(shù)attachToRoot為 false,則會設置layout params
temp.setLayoutParams(params);
}
}
//C 如果設置了root并且第三個參數(shù)為true.則使用params把temp添加 的root上去
if (root != null && attachToRoot) {
root.addView(temp, params);
}
//A 如果root沒設置并且第三參數(shù)為false
//則直接返回temp
if (root == null || !attachToRoot) {
result = temp;
}
/*
A:返回的是temp
B:返回的是root,temp設置了params,但沒有添加 到root上
C:返回的是root并且會把布局添加到root上
*/
return result;
}
對定義view的影響
onMeasure()方法都會根據(jù)測量模式做不同處理
MeasureSpec.EXACTLY == LayoutParams. MATCH_PARENT或設置的一個精確值
MeasureSpec.AT_MOST == LayoutParams. WRAP_CONTENT
可以知曉測量時依賴于LayoutParams。而inflate(resId,null)是不會設置LayoutParams的。
在listview中出現(xiàn)item設置的寬高沒有被處理的時候可以檢查一下是否正確調(diào)用了inflate方法