1. 程式人生 > >inflate()方法詳解和原始碼分析

inflate()方法詳解和原始碼分析

在開發中,我們經常需要使用到LayoutInflater,通過該物件的inflate()方法,將一個layout佈局檔案例項化為View物件。

關於LayoutInflater物件的獲取,參考博文:
http://blog.csdn.net/ruancoder/article/details/51760942

今天主要對inflate()方法的使用和原始碼進行分析。

(1).inflate()方法的使用

在實際使用中,我們一般會用到inflate的以下兩個過載方法。


方法一:
public View inflate(int resource, ViewGroup root) {}

方法二:
public View inflate(int resource, ViewGroup root, boolean attachToRoot) {}

其中方法一最為常見。
常見使用案例一:
View myView = LayoutInflater.from(context).inflate(R.layout.my_view, null);
將佈局檔案/res/layout/my_view.xml例項化為myView物件。

常見使用案例二:
ViewGroup viewRoot;
LayoutInflater.from(context).inflate(R.layout.my_view, viewRoot);
將佈局檔案/res/layout/my_view.xml例項化的View物件新增到viewRoot佈局中。

那麼方法一與方法二有什麼區別呢?
進入方法一的原始碼,我們會發現內部呼叫的其實就是方法二,只是將方法二的第3個引數設為“root != null”。
public View inflate(int resource, ViewGroup root) {
    return inflate(resource, root, root != null);
}

方法二中的引數和返回值釋義:
引數:
resource:需要例項化的佈局資源id。
root:ViewGroup型別檢視組物件
attachToRoot:是否將resource例項化後的View新增到引數root中。
返回值:
如果root為空,直接返回resource例項化後的View物件;
如果root不為空,attachToRoot為true,將resource例項化為view物件,忽略view的最外層檢視在xml佈局中定義的屬性,將view新增到root中,並將root返回。
如果root不為空,attachToRoot為false,將resource例項化為view物件,為view的最外層檢視設定其在xml佈局中定義的屬性,並將view物件返回。

(2).inflate()方法的原始碼分析

進入inflate()方法內部。
public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
    final Resources res = getContext().getResources();
    // 根據layout resource id,獲取該佈局的XmlResourceParser物件
    final XmlResourceParser parser = res.getLayout(resource);
    try {
        return inflate(parser, root, attachToRoot);
    } finally {
        parser.close();
    }
}
從方法內部可以看到,LayoutInflater使用的是pull解析器來解析xml佈局檔案的。獲取到佈局resource的XmlResourceParser物件後,接著進入下一個方法。

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {


    // ...


    // attrs是傳入的佈局layout在xml檔案裡面設定的屬性集合
    final AttributeSet attrs = Xml.asAttributeSet(parser);


    // 將ViewGroup型別的引數root賦值給result
    View result = root;


    // temp是傳入的引數resource的根佈局View
    final View temp = createViewFromTag(root, name, inflaterContext, attrs);


    ViewGroup.LayoutParams params = null;


    // 例項化temp檢視內的所有子檢視
    rInflateChildren(parser, temp, attrs, true);


    if (root != null) {
        // 根據attrs屬性集,建立佈局引數params
        params = root.generateLayoutParams(attrs);
	// 如果temp不需要新增到root中,那麼為temp設定佈局引數params
        if (!attachToRoot) {
            temp.setLayoutParams(params);
        }
    }


    if (root != null && attachToRoot) {
        // 將temp新增到root中,並使用佈局引數params
        root.addView(temp, params);
    }


    if (root == null || !attachToRoot) {
        // 將temp賦值給result(在此之前,result==root)
        result = temp;
    }


    // ...


    return result;
}
該方法是inflate()的關鍵,這裡只抽取了需要關注的核心程式碼。

最開始,定義方法的返回值result,將引數root賦值給result,例項化引數resource賦值給temp。
接下來進入判斷條件。
當root!=null時,根據resource的最外層view在xml中定義的的屬性,建立佈局引數params。如果!attachToRoot,為temp設定佈局引數params。
當root!=null&&attachToRoot,將temp新增到root中,並使用上面建立的佈局引數params。
當root==null||!attachToRoot,將temp賦值給result。
最後,將result返回。

邏輯看起來較繁瑣,簡單點可以這麼理解。
只要root==null,無視attachToRoot的值,建立temp物件,返回temp。
當root!=null時,分兩種情況。一,attachToRoot==true,將temp新增到root中,並使用佈局引數params,返回root。二,attachToRoot==false,為temp設定佈局引數params,返回temp。

(3).inflate()方法程式碼示例
在上面對inflate(int resource, ViewGroup root, boolean attachToRoot)方法的原始碼分析中,關於引數和返回值及其中的邏輯不難理解,主要是方法內是否為temp設定佈局引數有些難以理解。下面使用程式碼示例進行說明。

建立MainActivity,並設定介面佈局activity_main.xml。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"/>

新建一個textview.xml。這裡故意給TextView的layout_width和layout_height設定了固定數值,並新增layout_gravity屬性。方便後面看出差異。
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="230dp"
          android:layout_height="80dp"
          android:layout_gravity="center_horizontal"
          android:background="#999999"
          android:text="blog.csdn.net/ruancoder"
          android:textColor="#ffffff"
          android:textSize="18sp"/>

在MainActivity的onCreate()方法中,新增如下程式碼。
<pre name="code" class="java">package net.csdn.blog.ruancoder;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewGroup root = (ViewGroup) findViewById(R.id.layout);
        View textView = LayoutInflater.from(this).inflate(R.layout.textview, null);
        root.addView(textView);
    }
}


執行效果圖一:然後,將onCreate()方法中的程式碼修改為如下:
ViewGroup root = (ViewGroup) findViewById(R.id.layout);
LayoutInflater.from(this).inflate(R.layout.textview, root, true);

ViewGroup root = (ViewGroup) findViewById(R.id.layout);
View textView = LayoutInflater.from(this).inflate(R.layout.textview, root, false);
root.addView(textView);
兩種方式中的任意一種。

然後再看執行效果。

執行效果圖二:


從圖一的顯示效果可以看出,我們為TextView設定的layout屬性都失去了作用。而在圖二中,這三個layout屬性都正常顯示出來了。