Android 掃盲 - LayoutInflater

LayoutInflater 顧名思義,就是解析 xml ,生成相應的 view 出來,在 activity 中我們可以 findviewbyid 獲取到布局文件中的 view ,若是我們想要的 view 不在 activity 的布局文件中,那么就得通過 LayoutInflater 來獲取了

LayoutInflater 對象有3種獲取方式:

// 獲取上下文對象的 LayoutInflater 
LayoutInflater layoutInflater1 = context.getLayoutInflater();

// 自行初始化一個出來
LayoutInflater layoutInflater2 = LayoutInflater.from(this);

// 獲取系統服務
LayoutInflater layoutInflater3 = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

上述3種方式其實沒有區別,比如 activity.getLayoutInflater() 內部即使通過 LayoutInflater.from(this) 實現的,而 LayoutInflater.from(this) 又是通過 getSystemService(Context.LAYOUT_INFLATER_SERVICE) 實現了,只不過是進一步的封裝罷了

但是有區別的地方來了,在于 LayoutInflater 的加載方法

LayoutInflater 的加載方法有2個:

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root)

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)

解釋一下參數:

  • resource:xml 文件的 id
  • root:一個可選的 ViewGroup 對象
  • attachToRoot:是否將生成的視圖 add 到 root 上

這里我就不貼源碼了,說下結論,沒有興趣的去看源碼,沒幾行

  1. root 這個 ViewGroup 是用來給我們生成的 view 生成 LayoutParams 參數的,若是傳入的 root 是 null ,那么我們生成的 view 的 LayoutParams 就是空的,此時系統會自動給 view 生成 寬高都是 match_parent 的 LayoutParams 屬性對象。若 root 不為 null ,那么就會根據 xml 的配置來生成 LayoutParams 數據

  2. 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>
root = null 時
attachToRoot = false 時
attachToRoot = true 時
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容