LayoutInflater 顧名思義欣簇,就是解析 xml ,生成相應(yīng)的 view 出來屠阻,在 activity 中我們可以 findviewbyid 獲取到布局文件中的 view 馍盟,若是我們想要的 view 不在 activity 的布局文件中梆奈,那么就得通過 LayoutInflater 來獲取了
LayoutInflater 對象有3種獲取方式:
// 獲取上下文對象的 LayoutInflater
LayoutInflater layoutInflater1 = context.getLayoutInflater();
// 自行初始化一個出來
LayoutInflater layoutInflater2 = LayoutInflater.from(this);
// 獲取系統(tǒng)服務(wù)
LayoutInflater layoutInflater3 = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
上述3種方式其實(shí)沒有區(qū)別,比如 activity.getLayoutInflater() 內(nèi)部即使通過 LayoutInflater.from(this) 實(shí)現(xiàn)的袜蚕,而 LayoutInflater.from(this) 又是通過 getSystemService(Context.LAYOUT_INFLATER_SERVICE) 實(shí)現(xiàn)了糟把,只不過是進(jìn)一步的封裝罷了
但是有區(qū)別的地方來了,在于 LayoutInflater 的加載方法
LayoutInflater 的加載方法有2個:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root)
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
解釋一下參數(shù):
- resource:xml 文件的 id
- root:一個可選的 ViewGroup 對象
- attachToRoot:是否將生成的視圖 add 到 root 上
這里我就不貼源碼了牲剃,說下結(jié)論遣疯,沒有興趣的去看源碼,沒幾行
root 這個 ViewGroup 是用來給我們生成的 view 生成 LayoutParams 參數(shù)的凿傅,若是傳入的 root 是 null 缠犀,那么我們生成的 view 的 LayoutParams 就是空的,此時系統(tǒng)會自動給 view 生成 寬高都是 match_parent 的 LayoutParams 屬性對象聪舒。若 root 不為 null 辨液,那么就會根據(jù) xml 的配置來生成 LayoutParams 數(shù)據(jù)
attachToRoot 決定我們是不是把新生成的 view 添加到 root 里
最后我們看圖來加深下印象
layout_root:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_root"
android:orientation="vertical"
android:layout_width="300dp"
android:layout_height="400dp"
android:background="@color/forestgreen"
>
<TextView
android:id="@+id/tv_root_ll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LL and root"
android:layout_gravity="center_horizontal"
android:textSize="20sp"
/>
</LinearLayout>
layout_child:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_child"
android:orientation="vertical"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="@color/violet"
>
<TextView
android:id="@+id/tv_child_ll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LL and child"
android:layout_gravity="center_horizontal"
android:textSize="20sp"
/>
</LinearLayout>