天天看點

inflate 使用對比

LayoutInflater inflater = LayoutInflater.from(context);
View inflate1 = View.inflate(getActivity(), R.layout.test_main, null);
View inflate2 = inflater.inflate(R.layout.test_main, null);
View inflate3 = inflater.inflate(R.layout.test_main, null, false); // false 無意義
View inflate4 = inflater.inflate(R.layout.test_main, null, true);  // true 無意義
View inflate5 = inflater.inflate(R.layout.test_main, container, true);
View inflate6 = inflater.inflate(R.layout.test_main, container, false);
           
1.View inflate1 = View.inflate(getActivity(), R.layout.test_main, null);
調用了以下方法,本質還是同下面 inflate2 一樣
      
public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
    LayoutInflater factory = LayoutInflater.from(context);
    return factory.inflate(resource, root);
}
           
2.View inflate2 = inflater.inflate(R.layout.test_main, null);
調用了以下方法,本質還是同下面 inflate3 一樣
      
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
    return inflate(resource, root, root != null);
}
           
3.View inflate3 = inflater.inflate(R.layout.test_main, null, false);
4.View inflate4 = inflater.inflate(R.layout.test_main, null, true);
解析并加載 return view, 如果root為null,attachToRoot将失去作用,設定任何值都沒有意義
5.View inflate5 = inflater.inflate(R.layout.test_main, container, true);
加載view到container
6.View inflate6 = inflater.inflate(R.layout.test_main, container, false);
将布局外層的所有layout屬性進行設定,當該view被添加到父view當中時,這些layout屬性會自動生效。      

推薦郭大神的分析和結論:

1. 如果root為null,attachToRoot将失去作用,設定任何值都沒有意義。

2. 如果root不為null,attachToRoot設為true,則會給加載的布局檔案的指定一個父布局,即root。

3. 如果root不為null,attachToRoot設為false,則會将布局檔案最外層的所有layout屬性進行設定,當該view被添加到父view當中時,這些layout屬性會自動生效。

4. 在不設定attachToRoot參數的情況下,如果root不為null,attachToRoot參數預設為true。