Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 源碼系列(四)從源碼透視 LayoutInflater.Factory(上)

編輯:關於 Android 程式設計

現在幾乎每一款稍有體量的 App 都會提供主題切換能力,日間模式與夜間模式更是標配。QQ、網易新聞這類產品之所以口碑好,很大一部分原因就是這類細節做得細膩。仔細觀察你會發現,所謂「換膚」大多數時候並沒有替換掉整棵視圖樹,而是在換背景圖、換背景色、換文字顏色的層面上做功夫。

那麼,如果我們自己想實現一套主題切換框架,應該從哪裡下手?答案藏在 LayoutInflater 裡。本文先不涉及具體實現,而是把渲染鏈路和 Factory 機制從源碼層面梳理清楚,下一篇再用完整案例落地。如果你對這塊已經很熟,可以直接跳到文末。

一、LayoutInflater 的四種獲取姿勢

只要想把一份 layout.xml 變成真正的 View 層級結構,就繞不開 LayoutInflater。它在 Adapter 的 getView()、Fragment 的 onCreateView() 裡幾乎無處不在。常見的獲取方式有四種:

方式一:通過 Context.getSystemService()

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rootView = inflater.inflate(R.layout.view_layout, null);

方式二:LayoutInflater.from()

LayoutInflater inflater = LayoutInflater.from(context);
View rootView = inflater.inflate(R.layout.view_layout, null);

方式三:Activity 直接調用 getLayoutInflater()

LayoutInflater inflater = getLayoutInflater();
View rootView = inflater.inflate(R.layout.view_layout, null);

方式四:View 的靜態方法 inflate()

rootView = View.inflate(context, R.layout.view_layout, null);

四種寫法最終拿到的都是同一個東西,也都靠 inflate() 完成渲染。關鍵問題是:它們拿到的是不是同一個實例?

二、四種方式其實殊途同歸

先看 LayoutInflater.from() 的實現:

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;
}

很直白,它就是方式一的一層封裝,最終仍然落到 Context.getSystemService()。也就是說,只要傳入的 Context 相同,方式一與方式二拿到的必然是同一個實例。

再看方式三。Activity 的實現只是轉了一手:

public LayoutInflater getLayoutInflater() {
    return getWindow().getLayoutInflater();
}

Window 是抽象類,Android 中的實現類是 PhoneWindow,它直接返回一個成員變量:

@Override
public LayoutInflater getLayoutInflater() {
    return mLayoutInflater;
}

那 mLayoutInflater 從哪來?在 PhoneWindow 的構造函數裡:

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

繞了一圈,還是 LayoutInflater.from()。只要 PhoneWindow 持有的 Context 與前面一致,實例自然也是同一個。

最後是方式四,View.inflate() 依然是轉發:

public static View inflate(Context context, int resource, ViewGroup root) {
    LayoutInflater factory = LayoutInflater.from(context);
    return factory.inflate(resource, root);
}

結論很清晰:渲染 View 一定經過 LayoutInflater,而 LayoutInflater 由 Context 提供,Context 相同則實例相同。 這也正是後文能夠「統一管控」所有 View 的前提。

三、setContentView 也走同一條路

那 Activity 在 onCreate() 裡調用的 setContentView() 呢?

public void setContentView(int layoutResID) {
    getWindow().setContentView(layoutResID);
    initActionBar();
}

又是一次轉發,落到 PhoneWindow:

@Override
public void setContentView(int layoutResID) {
    if (mContentParent == null) {
        installDecor();
    } else {
        mContentParent.removeAllViews();
    }
    // 依然是 LayoutInflater 的 inflate()
    mLayoutInflater.inflate(layoutResID, mContentParent);
    final Callback cb = getCallback();
    if (cb != null && !isDestroyed()) {
        cb.onContentChanged();
    }
}

所以不論是我們手動渲染,還是系統幫我們設置內容,走的都是同一條 inflate() 通路。

四、Factory 與 Factory2:官方留下的鉤子

打開 LayoutInflater 源碼,你會看到內部定義了 Factory 和 Factory2 兩個接口,後者是對前者的補充擴展。先看 Factory:

public interface Factory {
    /**
     * Hook you can supply that is called when inflating from a LayoutInflater.
     * You can use this to customize the tag names available in your XML
     * layout files.
     *
     * Note that it is good practice to prefix these custom names with your
     * package (i.e., com.coolcompany.apps) to avoid conflicts with system
     * names.
     *
     * @param name  Tag name to be inflated.
     * @param context The context the view is being created in.
     * @param attrs Inflation attributes as specified in XML file.
     *
     * @return View Newly created view. Return null for the default
     *                   behavior.
     */
    public View onCreateView(String name, Context context, AttributeSet attrs);
}

註釋裡的關鍵詞是 Hook:LayoutInflater 在把標籤變成 View 的過程中,會先問一句「你有沒有興趣自己造這個 View?」這就是我們切入的入口。官方還貼心地提醒:自定義標籤名最好加上包名前綴,避免和系統標籤撞名。

五、inflate() 到底做了什麼

要理解 Hook 的時機,得跟一遍 inflate 的調用鏈。最外層只是轉發:

public View inflate(int resource, ViewGroup root) {
    return inflate(resource, root, root != null);
}

接著拿到解析器:

public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
    XmlResourceParser parser = getContext().getResources().getLayout(resource);
    try {
        return inflate(parser, root, attachToRoot);
    } finally {
        parser.close();
    }
}

核心邏輯在接收 XmlPullParser 的那個重載裡,我剝掉日誌與異常處理後的骨架如下:

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
    synchronized (mConstructorArgs) {
        final AttributeSet attrs = Xml.asAttributeSet(parser);
        Context lastContext = (Context) mConstructorArgs[0];
        mConstructorArgs[0] = mContext;
        View result = root;
        try {
            // 找到根節點
            int type;
            while ((type = parser.next()) != XmlPullParser.START_TAG
                    && type != XmlPullParser.END_DOCUMENT) {
                // 空循環
            }
            if (type != XmlPullParser.START_TAG) {
                throw new InflateException(parser.getPositionDescription()
                        + ": No start tag found!");
            }
            final String name = parser.getName();

            if (TAG_MERGE.equals(name)) {
                if (root == null || !attachToRoot) {
                    throw new InflateException("<merge> can be used only with a valid "
                            + "ViewGroup root and attachToRoot=true");
                }
                rInflate(parser, root, attrs, false);
            } else {
                View temp;
                if (TAG_1995.equals(name)) {
                    temp = new BlinkLayout(mContext, attrs);
                } else {
                    temp = createViewFromTag(root, name, attrs);
                }
                ViewGroup.LayoutParams params = null;
                if (root != null) {
                    params = root.generateLayoutParams(attrs);
                    if (!attachToRoot) {
                        temp.setLayoutParams(params);
                    }
                }
                // 遞歸渲染所有子 View
                rInflate(parser, temp, attrs, true);
                if (root != null && attachToRoot) {
                    root.addView(temp, params);
                }
                if (root == null || !attachToRoot) {
                    result = temp;
                }
            }
        } catch (XmlPullParserException e) {
            InflateException ex = new InflateException(e.getMessage());
            ex.initCause(e);
            throw ex;
        } catch (IOException e) {
            InflateException ex = new InflateException(parser.getPositionDescription()
                    + ": " + e.getMessage());
            ex.initCause(e);
            throw ex;
        } finally {
            mConstructorArgs[0] = lastContext;
            mConstructorArgs[1] = null;
        }
        return result;
    }
}

整段代碼在做的事情可以概括為:遞歸解析 XML,逐個標籤地造出 View,最終組裝成一棵視圖樹返回。

具體流程是:先用 Xml.asAttributeSet() 把屬性鍵值對封裝成 AttributeSet;然後循環 parser.next() 找到根節點,找不到就拋 InflateException;拿到根標籤名之後分岔——如果是 merge,必須配合有效的 root 與 attachToRoot=true,直接對 root 遞歸填充;否則進入 else 分支,通過 createViewFromTag() 造出根 View,再交給 rInflate() 遞歸處理所有子節點。

六、createViewFromTag:Hook 的真正入口

View createViewFromTag(View parent, String name, AttributeSet attrs) {
    if (name.equals("view")) {
        name = attrs.getAttributeValue(null, "class");
    }
    try {
        View view;
        if (mFactory2 != null) {
            view = mFactory2.onCreateView(parent, name, mContext, attrs);
        } else if (mFactory != null) {
            view = mFactory.onCreateView(name, mContext, attrs);
        } else {
            view = null;
        }
        if (view == null && mPrivateFactory != null) {
            view = mPrivateFactory.onCreateView(parent, name, mContext, attrs);
        }
        if (view == null) {
            if (-1 == name.indexOf('.')) {
                view = onCreateView(parent, name, attrs);
            } else {
                view = createView(name, null, attrs);
            }
        }
        return view;
    } catch (InflateException e) {
        throw e;
    } catch (ClassNotFoundException e) {
        InflateException ie = new InflateException(attrs.getPositionDescription()
                + ": Error inflating class " + name);
        ie.initCause(e);
        throw ie;
    } catch (Exception e) {
        InflateException ie = new InflateException(attrs.getPositionDescription()
                + ": Error inflating class " + name);
        ie.initCause(e);
        throw ie;
    }
}

這段代碼的優先級非常明確:mFactory2 → mFactory → mPrivateFactory → 系統默認邏輯。任何一個 Factory 返回了非 null 的 View,系統就不再插手;只有全部返回 null,才會走默認流程:判斷標籤名裡有沒有「點」,沒有就補上前綴 android.view.,然後交給 public final 的 createView() 反射創建。

這裡還有一個容易踩坑的細節:LayoutInflater 內部有個布爾開關 mFactorySet,默認 false。一旦調用過 setFactory() 或 setFactory2(),它就變成 true,此後再次調用這兩個方法會直接拋異常。也就是說每個 LayoutInflater 實例只能綁定一次 Factory;想換成別的,只能反射把 mFactorySet 改回 false。這也是為什麼很多換膚框架會選擇自己 new 一個 LayoutInflater 或繞道反射的原因。

七、串起來看:換膚的思路

把上面的結論攏一下:

1. 所有 View 的創建都要經過 LayoutInflater.inflate();
2. inflate() 遞歸解析布局,每個標籤最終都交給 createViewFromTag();
3. createViewFromTag() 會優先詢問 Factory,Factory 是所有 View 誕生的統一入口。

於是換膚的骨架就出來了:在 Factory 的 onCreateView() 裡,先交給系統正常創建 View,創建完成後攔截下來;接著判斷這個 View 有沒有標記「需要換膚」——官方推薦的做法是自定義屬性,佈局裡出現了自定義屬性,就說明這個 View 參與換膚。把它收集進一個集合,等用戶切換主題時遍歷集合,批量更新背景、文字顏色等屬性即可。

由於篇幅原因,本篇先停在入口這一步。下一篇會用一個可運行的小項目,把 Factory 攔截、自定義屬性解析、資源屬性集中管理這幾件事完整串起來,敬請期待。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved