1. 程式人生 > >android inflate原始碼解析

android inflate原始碼解析

在開發中,我們經常使用Layoutinflater物件的inflate()方法,他是將xml佈局檔案例項化為一個view; 關於infalte使用: 我們常見的有兩種: 1)將xml檔案佈局例項化為View物件 LayoutInflater.from(context).inflate(int resoure,viewGroup root){} 2)將xml檔案佈局例項化為view物件,並新增到ViewRoot佈局中 ViewGroup viewRoot; LayoutInflater.from().inflate(int resoure,viewRoot){} 這個兩個常用的方法有什麼不同? 我們通過原始碼分析,主要是將方法的第三個引數中root設定為不是null; 下面我們通過原始碼來講解之間的區別: 從原始碼中可以看到: 1)final AttributeSet attrs = Xml.asAttributeSet(parser); 將子view的屬性賦值給attrs; 2 )View result = root; 首先聲明瞭View result=root;最終返回值為result 3)temp = createViewFromTag(root, name, attrs); temp = createViewFormTag(root,name,attrs); 這個是構建出一個子view 4)if (root != null) { params = root.generateLayoutParams(attrs);if (!attachToRoot) {temp.setLayoutParams(params);}} 通過上面的程式碼可知(原始碼被簡化) 如果 root!=null,並且attachToRoot為false; 建立temp,然後執行temp.setLayoutParams(params);返回temp(改變外層佈局的寬高) 5)// We are supposed to attach all the views we found (int temp // to root. Do that now. if (root != null && attachToRoot) {root.addView(temp, params); } 通過上面的原始碼可知; 如果root!=null,並且,並且attachToRoot為ture; 建立temp,然後執行root.addView(temp,params);最後返回root。 (把子view放到root裡,並把寬高設定上,) 6) if (root == null || !attachToRoot) {result = temp;} 通過上面的原始碼可知: 如果root==null,只建立temp,返回temp (沒有設定LayoutParams)在子view上。 通過上面原始碼的分析,得出結論: 1)當root!=null attachToRoot為false: 設定LayoutParams在子view上,改變xml佈局的寬高等屬性,(白話講解:舉例:listview 的item佈局指定了具體寬高,在listview列表顯示時:會相應這個寬高,) 2)當root!=null attachToRoot為true: 把子View放到root中,並改變xml佈局的寬高; 3)root==null; 沒有設定LayoutParams在子view上; 3.總結相關問題: adapterView不能用addView(),會報錯