在實際開發(fā)中LayoutInflater這個類還是非常有用的,它的作用類似findViewById()。不同點是LayoutInflater是用來找res/layout/下的xml布局文件,并且實例化;而findViewById()是找xml布局文件下的具體widget控件(如Button、TextView等)。
具體作用:
1、對于一個沒有被載入或者想要動態(tài)載入的界面,都需要使用
LayoutInflater.inflate()來載入;
2、對于一個已經載入的界面,就可以使用Activiyt.findViewById()方法來獲得其中的界面元素。
LayoutInflater 是一個抽象類,在文檔中如下聲明:
public abstract class LayoutInflater extends Object
獲得 LayoutInflater 實例的三種方式
- LayoutInflater inflater = getLayoutInflater();//調用Activity的getLayoutInflater()
- LayoutInflater inflater = LayoutInflater.from(context);
- LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
其實,這三種方式本質是相同的,從源碼中可以看出:
getLayoutInflater():
Activity 的 getLayoutInflater() 方法是調用 PhoneWindow 的getLayoutInflater()方法,看一下該源代碼:
public PhoneWindow(Context context)
{
super(context);
mLayoutInflater = LayoutInflater.from(context);
}
可以看出它其實是調用 LayoutInflater.from(context)。
LayoutInflater.from(context):
public static LayoutInflater from(Context context)
{
LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null)
{
throw new AssertionError("LayoutInflater not found.");
}
return LayoutInflater;
}
可以看出它其實調用 context.getSystemService()。
結論:
所以這三種方式最終本質是都是調用的Context.getSystemService()。
另外getSystemService()是Android很重要的一個API,它是Activity的一個方法,根據傳入的NAME來取得對應的Object,然后轉換成相應的服務對象。
好吧 上面好像都不是今天我最想說的 我是分割線
我們加載布局的方式一般以下兩種方式 :
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
...省略實現(xiàn)代碼...
}
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
...省略實現(xiàn)代碼...
}
總結:
1.如果root為null,attachToRoot將失去作用,設置任何值都沒有意義,加載的布局文件最外層的所有l(wèi)ayout屬性會失效,由父布局來重新指定.
2.如果root不為null,attachToRoot不論是true或false,加載的布局文件最外層的所有l(wèi)ayout屬性都有效,唯一的不同是:
attachToRoot為true時,會自動調用root.addView(view, params),最后返回root;
attachToRoot為false時,會返回view,需手動調用root.addView(view, params).
3.在不設置attachToRoot參數的情況下,如果root不為null,attachToRoot參數默認為true.
其實View.inflate(resource, R.layout.xx, root);完全等價于
LayoutInflater.from(resource).inflate(R.layout.,root,true);
直接看源碼發(fā)現(xiàn):
public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {
return inflate(parser, root, root != null);
}
詳細分析見:http://www.itdecent.cn/p/74bb29077690 多謝分享!