LayoutInflate
一妆绞、是什么?
LayoutInflate就是傳說中的布局泵,是用來找res/layout/下的xml布局文件邓夕,并且實例化刘莹;而findViewById()是找xml布局文件下的具體widget控件(如Button、TextView等)焚刚。
二点弯、實例化方法
LayoutInflater 實例的三種方式:
1. LayoutInflater inflater = getLayoutInflater();//調用Activity的getLayoutInflater()
2. LayoutInflater inflater = LayoutInflater.from(context);
3. LayoutInflater inflater = ?(LayoutInflater)context.getSystemService
另外getSystemService()是Android很重要的一個API,它是Activity的一個方法矿咕,根據(jù)傳入的NAME來取得對應的Object抢肛,然后轉換成相應的服務對象。所以碳柱,必須在activity的上下文環(huán)境下才能使用布局泵捡絮,不是想在哪里用就可以用的·;
三莲镣、加載布局 ?inflate(int resource, ViewGroup root,boolean attachToRoot)福稳;
1、 Inflate(resId , null )不能正確處理寬和高是因為:layout_width,layout_height是相對了父級設置的瑞侮,必須與父級的LayoutParams一致灵寺。而加載的view的getLayoutParams為null,不正常顯示区岗,源碼分析主要是沒有設置setLayoutParams(params)略板;
2、Inflate(resId , parent,false)加載的view 可以正確處理慈缔,因為加載的view設置了setLayoutParams(params);這個params正是父類布局generateLayoutParams(attrs);得到的,正常顯示叮称,原來參數(shù)設成什么就是什么
3、Inflate(resId , parent,true )不僅不能夠正確的處理藐鹤,并且返回的是parent瓤檐,和以上兩者返回值有絕對的區(qū)別;
4娱节、部分源碼解析
1挠蛉、默認返回的view 為 View result=root;root為傳進去的root;
2肄满、如果root為true 且attachToRoot則temp.setLayoutParams(params);
if(root!=null) {
params=root.generateLayoutParams(attrs);
if(!attachToRoot) {
temp.setLayoutParams(params);
}
3谴古、
final View temp= createViewFromTag(root,name,attrs,false); 從xml解析出來的view,及我們要顯示的view
4稠歉、如果root為null或者attachToRoot為false掰担,則返回的view 就是我們要顯示的view而不是父類view root
// Decide whether to return the root that was passed in or the
// top view found in xml.
if(root==null|| !attachToRoot) {
result=temp;
}
5、總結
使用 inflate(int resource, ViewGroup root,boolean attachToRoot)怒炸;带饱,一看父類root是誰,而看attachToRoot是否為true,如果要顯示的布局為 FrameLayout->button,傳入的root為FrameLayout勺疼,則返回的就是這個FrameLayout教寂;