文章目錄
-
- 一、LayoutInflater.inflate()
-
- 1. 擷取LayoutInflater執行個體
- 2. LayoutInflater.inflate()的重載
- 二、 View.inflate()
- 三、總結
一、LayoutInflater.inflate()
該方法适用于所有布局填充的的場景,但使用前需要先執行個體化LayoutInflater對象
1. 擷取LayoutInflater執行個體
-
getLayoutInflater();
這個方法可以在Activity和Fragment中使用,不過在Fragment中使用時,要傳入一個bundle參數
// Activity中使用 LayoutInflater layoutInflater = getLayoutInflater(); // Fragment中使用 LayoutInflater layoutInflater = getLayoutInflater(savedInstanceState);
-
getSystemService();
這個為Context的方法,隻要有上下文就能調用
LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-
LayoutInflater.from();
這個是LayoutInflater的靜态方法,傳入上下文即可
LayoutInflater inflater = LayoutInflater.from(this);
2. LayoutInflater.inflate()的重載
常用的是下面兩種:
- inflate(int resource,ViewGroup root,boolean attachToRoot)
- resource:布局資源id
- root:resource生成view對象要填入的父布局。為null,則傳回的view就是布局資源;否則,需要參照第三個參數
- attachToRoot:是否将resource生成view對象填入root,以root作為最終傳回view的根布局。 false,root不為null,則提供root的LayoutParams限制resource生成的view;true,root不為null,以root作為最終傳回view的根布局
- inflate(int resource,ViewGroup root)
- resource:布局資源
- root:resource生成view對象要填入的父布局。為null,則傳回的view就是布局資源的根布局;否則,傳回的view以傳入的root為根布局(相當于上面的那個第三個參數為true)
該方法,實際還是調用了上一個方法
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
二、 View.inflate()
這個是View類的靜态方法,可直接調用,實際上還是使用了LayoutInflater,是以,它沒有直接使用LayoutInflater.inflate()強大
public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}
參數含義:
- context:上下文
- resource:布局資源
- root:resource生成view對象要填入的父布局。為null,則傳回resource生成view對象,否則将view填入到root中,以root作為根布局傳回
三、總結
View.inflate()是封裝了LayoutInflater的inflate()方法,由于是靜态方法,比較簡便;但LayoutInflater相當于比View多了一個三個參數的inflate()方法,功能更強大
個人總結,水準有限,如果有錯誤,希望大家能給留言指正!如果對您有所幫助,可以幫忙點個贊!如果轉載,希望可以标明文章出處!最後,非常感謝您的閱讀!