View 編程(0): 認識 LayoutInflater

LayoutInflater 在 android 開發中使用頻率較高,需要留意!


該類是一個抽象類,在文檔中如下聲明:


public abstract class LayoutInflater extends Object


1.  獲得 LayoutInflater 實例

三種方法可以獲得該實例對象,方法如下:


a. LayoutInflater inflater = getLayoutInflater();


b. LayoutInflater localinflater =
  (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE); 


c. LayoutInflater inflater = LayoutInflater.from(context);


對於方法 a,主要是調用 Activity 的 getLayoutInflater() 方法。


繼續跟蹤研究 android 源碼,Activity 中的該方法是調用 PhoneWindow 的 getLayoutInflater()方法!


那麼,分享一下該源代碼:


public PhoneWindow(Context context) {
        super(context);
        mLayoutInflater = LayoutInflater.from(context);


可以看出它其實是調用 LayoutInflater.from(context), 那麼該方法其實是調用 b,看看源碼,如下:


   /**
     * Obtains the LayoutInflater from the given 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;

    }


2. inflate 方法

inflate 願意是充氣之類的,在這裏主要意思就是,擴張、使之膨脹。

換句話說就是將當前視圖view 補充完整、擴展該視圖。


通過 sdk 的 api 文檔,可以知道該方法有以下幾種過載形式,返回值均是 View 對象,如下:


public View inflate (int resource, ViewGroup root)

public View inflate (XmlPullParser parser, ViewGroup root)

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

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


示例代碼:


LayoutInflater inflater = (LayoutInflater)
getSystemService(LAYOUT_INFLATER_SERVICE);


/* R.id.test 是 custom.xml 中根(root)佈局 LinearLayout 的 id */
View view = inflater.inflate(R.layout.custom,

(ViewGroup)findViewById(R.id.test));


/* 通過該 view 實例化 EditText對象, 否則報錯,因爲當前視圖不是custom.xml.

即沒有 setContentView(R.layout.custom) 或者 addView() */

//EditText editText = (EditText)findViewById(R.id.content);// error

EditText editText = (EditText)view.findViewById(R.id.content);


對於上面代碼,指定了第二個參數 ViewGroup root,當然你也可以設置爲 null 值。


注意:該方法與 findViewById 方法不同。

inflater 是用來找 layout 下 xml 佈局文件,並且實例化!

而 findViewById() 是找具體 xml 下的具體 widget 控件(如: Button,TextView 等)。



更多關於 inflate 方法,請看 LayoutInflater 源碼。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章