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

Android LayoutInflater 原始碼解析與應用

編輯:關於 Android 程式設計

前言

如果是初學者,很可能對 LayoutInflater 不太熟悉,或許只在 Fragment 的 onCreateView() 中照著範式用過幾次。但只要累積一些工作經驗就會明白,這個類別有多重要——它是連接版面 XML 與 Java 程式碼的橋樑。

我們常會疑惑:為什麼 Android 支援用 XML 撰寫版面?答案自然是系統內部幫我們解析了這些檔案,而 LayoutInflater 就是負責這件事的角色。

一、LayoutInflater 是系統服務

從 from 方法就能看出這一點:

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

二、inflate 的重載關係

取得物件後通常會呼叫 inflate 載入版面。這是一個重載方法:

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

可見呼叫兩參數版本時,預設是否附加到父布局取決於 root 是否為空(父布局一般都不為空)。

public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
    final Resources res = getContext().getResources();
    if (DEBUG) {
        Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
                + Integer.toHexString(resource) + ")");
    }

    final XmlResourceParser parser = res.getLayout(resource);
    try {
        return inflate(parser, root, attachToRoot);
    } finally {
        parser.close();
    }
}

這個方法先用 Resources 把資源 ID 還原成 XmlResourceParser 物件,再呼叫 inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)。解析版面的具體步驟都在後者之中。

三、核心解析流程

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
    synchronized (mConstructorArgs) {
        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");

        final AttributeSet attrs = Xml.asAttributeSet(parser);
        Context lastContext = (Context) mConstructorArgs[0];
        mConstructorArgs[0] = mContext;
        View result = root;

        try {
            // 1. 循環尋找根節點,本質是指標遍歷的過程
            int type;
            while ((type = parser.next()) != XmlPullParser.START_TAG
                    && type != XmlPullParser.END_DOCUMENT) {
                // Empty
            }
            if (type != XmlPullParser.START_TAG) {
                throw new InflateException(parser.getPositionDescription() + ": No start tag found!");
            }

            // 2. 取得節點名稱,用於後續判斷
            final String name = parser.getName();
            if (DEBUG) {
                System.out.println("**************************");
                System.out.println("Creating root view: " + name);
                System.out.println("**************************");
            }

            // 3. 若節點名為 merge,依其特性必須附加到父布局
            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, false);
            } else {
                // 4. 依節點名稱建立 View
                // Temp is the root view that was found in the xml
                final View temp = createViewFromTag(root, name, attrs, false);
                ViewGroup.LayoutParams params = null;

                if (root != null) {
                    // 5. 依 attrs 產生版面參數
                    params = root.generateLayoutParams(attrs);
                    if (!attachToRoot) {
                        // 6. 若不附加到父布局,就把參數設給自己
                        temp.setLayoutParams(params);
                    }
                }

                // 7. 載入該節點下的所有子 View
                rInflate(parser, temp, attrs, true, true);

                // 8. 若需附加,直接 addView
                if (root != null && attachToRoot) {
                    root.addView(temp, params);
                }

                // 9. 若不附加,則回傳自己
                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 {
            // Don't retain static reference on context.
            mConstructorArgs[0] = lastContext;
            mConstructorArgs[1] = null;
        }

        Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        return result;
    }
}

核心步驟可以濃縮成三句話:

1、找到根布局標籤
2、建立根節點對應的 View
3、建立其子 View

由此可見,子 View 的解析全交由 rInflate 處理;若 XML 中有根布局,則先呼叫 createViewFromTag 建立根 View。merge 的作用也在這裡得到解釋:它直接呼叫 rInflate 把自己添加到父 View,比較 rInflate(parser, root, attrs, false, false) 與 rInflate(parser, temp, attrs, true, true) 的第二個參數差異就能明白。

四、rInflate 如何建立多層布局

void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs,
              boolean finishInflate, boolean inheritContext) throws XmlPullParserException, IOException {

    // 取得目前解析器指針所在節點的布局層次
    final int depth = parser.getDepth();
    int type;

    // 進行樹的深度優先遍歷(若節點有子節點會再次進入 rInflate,否則繼續循環)
    while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth)
            && type != XmlPullParser.END_DOCUMENT) {
        if (type != XmlPullParser.START_TAG) {
            continue;
        }

        final String name = parser.getName();

        if (TAG_REQUEST_FOCUS.equals(name)) {
            // 遇到 request_focus 標籤,為該 View 設定焦點
            parseRequestFocus(parser, parent);
        } else if (TAG_TAG.equals(name)) {
            // 遇到 tag 標籤,為該 View 設定 tag(key, value)
            parseViewTag(parser, parent, attrs);
        } else if (TAG_INCLUDE.equals(name)) {
            // 遇到 include 標籤
            if (parser.getDepth() == 0) {
                throw new InflateException("<include /> cannot be the root element");
            }
            parseInclude(parser, parent, attrs, inheritContext);
        } else if (TAG_MERGE.equals(name)) {
            throw new InflateException("<merge /> must be the root element");
        } else {
            // 建立該節點代表的 View 並加入父 view,同時遞迴遍歷子節點
            final View view = createViewFromTag(parent, name, attrs, inheritContext);
            final ViewGroup viewGroup = (ViewGroup) parent;
            final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
            rInflate(parser, view, attrs, true, true);
            viewGroup.addView(view, params);
        }
    }

    // 代表一個節點(含其子節點)遍歷結束
    if (finishInflate) {
        parent.onFinishInflate();
    }
}

五、createViewFromTag 的降級策略

View createViewFromTag(View parent, String name, AttributeSet attrs, boolean inheritContext) {
    if (name.equals("view")) {
        name = attrs.getAttributeValue(null, "class");
    }

    Context viewContext;
    if (parent != null && inheritContext) {
        viewContext = parent.getContext();
    } else {
        viewContext = mContext;
    }

    // 若有指定主題,套用主題包裝
    final TypedArray ta = viewContext.obtainStyledAttributes(attrs, ATTRS_THEME);
    final int themeResId = ta.getResourceId(0, 0);
    if (themeResId != 0) {
        viewContext = new ContextThemeWrapper(viewContext, themeResId);
    }
    ta.recycle();

    if (name.equals(TAG_1995)) {
        // Let's party like it's 1995!
        return new BlinkLayout(viewContext, attrs);
    }

    if (DEBUG) System.out.println("******** Creating view: " + name);

    try {
        View view;
        if (mFactory2 != null) {
            view = mFactory2.onCreateView(parent, name, viewContext, attrs);
        } else if (mFactory != null) {
            view = mFactory.onCreateView(name, viewContext, attrs);
        } else {
            view = null;
        }

        if (view == null && mPrivateFactory != null) {
            view = mPrivateFactory.onCreateView(parent, name, viewContext, attrs);
        }

        if (view == null) {
            final Object lastContext = mConstructorArgs[0];
            mConstructorArgs[0] = viewContext;
            try {
                if (-1 == name.indexOf('.')) {
                    view = onCreateView(parent, name, attrs);
                } else {
                    view = createView(name, null, attrs);
                }
            } finally {
                mConstructorArgs[0] = lastContext;
            }
        }

        if (DEBUG) System.out.println("Created view is: " + view);
        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;
    }
}

簡化之後就是四層降級:

if (factory2 != null) {
    factory2.onCreateView();
} else if (factory != null) {
    factory.onCreateView();
} else if (mPrivateFactory != null) {
    mPrivateFactory.onCreateView();
} else {
    onCreateView();
}

其他的 onCreateView 若我們不去設定就是 null,因此實務上多半會走到最後一層。而這個方法內部又會呼叫 createView():

public final View createView(String name, String prefix, AttributeSet attrs)
        throws ClassNotFoundException, InflateException {

    // 從建構器快取中取得對應的建構器
    Constructor<? extends View> constructor = sConstructorMap.get(name);
    Class<? extends View> clazz = null;

    try {
        Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);

        if (constructor == null) {
            // 快取中沒有,透過 ClassLoader 載入對應的類別
            clazz = mContext.getClassLoader().loadClass(
                    prefix != null ? (prefix + name) : name).asSubclass(View.class);

            if (mFilter != null && clazz != null) {
                boolean allowed = mFilter.onLoadClass(clazz);
                if (!allowed) {
                    failNotAllowed(name, prefix, attrs);
                }
            }

            // 將使用過的建構器快取起來
            constructor = clazz.getConstructor(mConstructorSignature);
            sConstructorMap.put(name, constructor);
        } else {
            // 若設有 filter,仍要對快取中的建構器套用檢查
            if (mFilter != null) {
                Boolean allowedState = mFilterMap.get(name);
                if (allowedState == null) {
                    clazz = mContext.getClassLoader().loadClass(
                            prefix != null ? (prefix + name) : name).asSubclass(View.class);
                    boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
                    mFilterMap.put(name, allowed);
                    if (!allowed) {
                        failNotAllowed(name, prefix, attrs);
                    }
                } else if (allowedState.equals(Boolean.FALSE)) {
                    failNotAllowed(name, prefix, attrs);
                }
            }
        }

        Object[] args = mConstructorArgs;
        args[1] = attrs;
        constructor.setAccessible(true);

        // 透過反射建立對應的實例
        final View view = constructor.newInstance(args);

        if (view instanceof ViewStub) {
            // 使用相同的 context 來 inflate ViewStub
            final ViewStub viewStub = (ViewStub) view;
            // ViewStub 會建立一個屬於自己的 LayoutInflater,因為它需要在不同時機去 inflate
            viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
        }
        return view;

    } catch (NoSuchMethodException e) {
        InflateException ie = new InflateException(attrs.getPositionDescription()
                + ": Error inflating class " + (prefix != null ? (prefix + name) : name));
        ie.initCause(e);
        throw ie;
    } catch (ClassCastException e) {
        // 若載入的類別不是 View 的子類
        InflateException ie = new InflateException(attrs.getPositionDescription()
                + ": Class is not a View " + (prefix != null ? (prefix + name) : name));
        ie.initCause(e);
        throw ie;
    } catch (ClassNotFoundException e) {
        // 若 loadClass 失敗,直接向上拋出
        throw e;
    } catch (Exception e) {
        InflateException ie = new InflateException(attrs.getPositionDescription()
                + ": Error inflating class " + (clazz == null ? "<unknown>" : clazz.getName()));
        ie.initCause(e);
        throw ie;
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_VIEW);
    }
}

大致流程為:

1、從快取中取得特定 View 的建構器;若無,則載入對應類別並快取該建構器
2、利用建構器反射建立對應的 View
3、若是 ViewStub,則複製一個 LayoutInflater 物件傳給它

把這條線索串起來看,就能理解為什麼自訂 View 必須提供 (Context, AttributeSet) 這個建構子——因為 inflate 正是透過反射呼叫它。同時也能明白 sConstructorMap 這個靜態快取的存在,讓同一個 View 類別只需反射一次,是版面載入效能的重要保障。

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