首頁 > 軟體

原始碼分析Android LayoutInflater的使用

2023-10-16 22:00:46

LayoutInflater

開頭先附一段LayoutInflater類的註釋簡介

/**
 * Instantiates a layout XML file into its corresponding {@link android.view.View}
 * objects. It is never used directly. Instead, use
 * {@link android.app.Activity#getLayoutInflater()} or
 * {@link Context#getSystemService} to retrieve a standard LayoutInflater instance
 * that is already hooked up to the current context and correctly configured
 * for the device you are running on.
 *
 * To create a new LayoutInflater with an additional {@link Factory} for your
 * own views, you can use {@link #cloneInContext} to clone an existing
 * ViewFactory, and then call {@link #setFactory} on it to include your
 * Factory.
 *
 * For performance reasons, view inflation relies heavily on pre-processing of
 * XML files that is done at build time. Therefore, it is not currently possible
 * to use LayoutInflater with an XmlPullParser over a plain XML file at runtime;
 * it only works with an XmlPullParser returned from a compiled resource
 * (R.<em>something</em> file.)
 */

這是LayoutInflater開頭的一段介紹,我們能看到幾個重要的資訊:

  • LayoutInfalter的作用是把XML轉化成對應的View物件,需要用Activity#getLayoutInflater()或者getSystemService獲取,會繫結當前的Context
  • 如果需要使用自定義的Factory檢視替換載入資訊,需要用cloneInContext去克隆一個ViewFactory,然後呼叫setFactory設定自定義的Factory
  • 效能原因,inflate會在build階段進行,無法用來載入一個外部文字XML檔案,只能載入R.xxx.xxx這種處理好的資原始檔。
//LayoutInflater.java
    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
	//root是否為null來決定attachToRoot是否為true。
        return inflate(resource, root, root != null);
    }
    public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {
        return inflate(parser, root, root != null);
    }
    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
        ...

        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }
//三個inflate方法最終都會呼叫到下面這個三個引數的inflate方法。
    /**
     * parser XML節點包含了View的層級描述
     * root 需要attached到的根目錄,如果attachToRoot為true則root必須不為null。
     * attachToRoot 載入的層級是否需要attach到rootView,
     * return attachToRoot為true,就返回root,反之false就返回載入的XML檔案的根節點View。
     */
    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {

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

            try {
                // Look for the root node.
                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!");
                }
                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, inflaterContext, attrs, false);
                } else {
                    // Temp is the root view that was found in the xml
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                    ViewGroup.LayoutParams params = null;
                    if (root != null) {
                        // Create layout params that match root, if supplied
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            temp.setLayoutParams(params);
                        }
                    }

                    rInflateChildren(parser, temp, attrs, true);

...
                    // We are supposed to attach all the views we found (int temp) to root. Do that now.
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                    // Decide whether to return the root that was passed in or the top view found in xml.
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }
            } catch (XmlPullParserException e) {
...
            }
            return result;
        }
    }

inflate方法使用XmlPullParser解析XML檔案,並根據得到的標籤名執行不同的邏輯:

  • 首先如果是merge標籤,會走rInflate方法,方法前面帶r的說明是recurse遞迴方法
  • 如果不是merge標籤,執行createViewFromTag,根據傳入的nameattrs獲取到name對應的rootView並且新增到root裡面。

針對merge標籤,如果是merge標籤必須有root並且必須attachToRoot==true,否則直接拋異常,所以我們得知merge必須作為root標籤使用,並且不能用在子標籤中①,rInflate方法中也會針對merge標籤進行檢查,保證merge標籤不會出現在子標籤中,後面會有介紹。
檢查通過則呼叫rInflate(parser, root, inflaterContext, attrs, false)方法,遞迴遍歷root的層級,解析載入childrenView掛載到parentView下面,rinflate詳細解析可以看rinflate

如果不是merge標籤則呼叫createViewFromTag(root, name, inflaterContext, attrs),這個方法的作用是載入名字為name的view,根據name反射方式建立對應的View,根據傳入的attrs構造Params設定給View,返回建立好的View。
當然這只是建立了一個View,需要再呼叫rInflateChildren(parser, temp, attrs, true),這個方法也是一個遞迴方法,它的作用是根據傳入的parser包含的層級,載入此層級的子View並掛載到temp下面。

createViewFromTag

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

        // Apply a theme wrapper, if allowed and one is specified.
        // 如果傳入的attr中包含theme屬性,則使用此attr中的theme。
        if (!ignoreThemeAttr) {
            final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
            final int themeResId = ta.getResourceId(0, 0);
            if (themeResId != 0) {
                context = new ContextThemeWrapper(context, themeResId);
            }
            ta.recycle();
        }

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

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

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

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

            return view;
        } catch (Exception e) {
            ...
        }
    }

先看當前標籤的attr屬性裡面是否設定了theme,如果設定了就用當前標籤的theme屬性,繫結到context上面。 這裡很有意思的是特殊判斷了一個TAG_1995,也就是blink,一個將包裹的內容每隔500ms顯示隱藏的一個標籤,怎麼看都像個彩蛋~

然後呼叫mFactory2onCreateView,如果沒有設定mFactory2就嘗試mFactory,否則呼叫mPrivateFactory,mFactory2和mFactory後面再說,這裡先往後走。

如果還是沒有載入到view,先判斷name,看名字裡是不是有.,如果沒有就表明是Android原生的View,最終都會呼叫到createView方法,onCreateView最終會呼叫到createView(name, "android.view.", attrs);,會在View名字天面新增"android.view."字首。

下面是預設的createView的實現:

    @Nullable
    public final View createView(@NonNull Context viewContext, @NonNull String name,
            @Nullable String prefix, @Nullable AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
        Objects.requireNonNull(viewContext);
        Objects.requireNonNull(name);
        Constructor<? extends View> constructor = sConstructorMap.get(name);
        if (constructor != null && !verifyClassLoader(constructor)) {
            constructor = null;
            sConstructorMap.remove(name);
        }
        Class<? extends View> clazz = null;

        try {
            if (constructor == null) {
                // Class not found in the cache, see if it's real, and try to add it
                clazz = Class.forName(prefix != null ? (prefix + name) : name, false,
                        mContext.getClassLoader()).asSubclass(View.class);

                if (mFilter != null && clazz != null) {
                    boolean allowed = mFilter.onLoadClass(clazz);
                    if (!allowed) {
                        failNotAllowed(name, prefix, viewContext, attrs);
                    }
                }
                constructor = clazz.getConstructor(mConstructorSignature);
                constructor.setAccessible(true);
                sConstructorMap.put(name, constructor);
            } else {
                // If we have a filter, apply it to cached constructor
                if (mFilter != null) {
                    // Have we seen this name before?
                    Boolean allowedState = mFilterMap.get(name);
                    if (allowedState == null) {
                        // New class -- remember whether it is allowed
                        clazz = Class.forName(prefix != null ? (prefix + name) : name, false,
                                mContext.getClassLoader()).asSubclass(View.class);

                        boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
                        mFilterMap.put(name, allowed);
                        if (!allowed) {
                            failNotAllowed(name, prefix, viewContext, attrs);
                        }
                    } else if (allowedState.equals(Boolean.FALSE)) {
                        failNotAllowed(name, prefix, viewContext, attrs);
                    }
                }
            }

            Object lastContext = mConstructorArgs[0];
            mConstructorArgs[0] = viewContext;
            Object[] args = mConstructorArgs;
            args[1] = attrs;

            try {
                final View view = constructor.newInstance(args);
                if (view instanceof ViewStub) {
                    // Use the same context when inflating ViewStub later.
                    final ViewStub viewStub = (ViewStub) view;
                    viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
                }
                return view;
            } finally {
                mConstructorArgs[0] = lastContext;
            }
        } catch (Exception e) {
            ...
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
    }

這個方法可以看到View是怎麼建立出來的,用類的全限定名拿到class資訊,有一個sConstructorMap快取類的constructor,如果能拿到有效的構造器就不再重複建立來提升效率,如果沒有快取的構造器,就反射得到構造器並新增到sConstructorMap中以便後面使用。這裡有個mFilter來提供自定義選項,使用者可以自定義哪些類不允許構造。

拿到構造器之後,實際上newInstance是呼叫了兩View個引數的構造方法。第一個引數是Context,第二個引數是attrs,這樣我們就得到了需要載入的View。

這裡可以結合LayoutInflater.Factory2一起來看,Activity實際上是實現了LayoutInflater.Factory2介面的:

//Activity.java
    public View onCreateView(@NonNull String name, @NonNull Context context,
            @NonNull AttributeSet attrs) {
        return null;
    }

所以我們可以直接在Activity裡面重寫onCreateView方法,這樣就可以根據View的名字來實現我們的一些操作,比如換膚的操作,比如定義一個名字來表示某種自定義View。可以看這樣一個用法:

    <PlaceHolder
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="include LinearLayout"
        android:textColor="#fff"
        android:textSize="15sp" />

然後我們在重寫的onCreateView裡面判斷name:

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        if ("PlaceHolder".equals(name)) {
            return new TextView(this, attrs);
        }
        return super.onCreateView(name, context, attrs);
    }

這樣其實就不拘泥於名字可以自己建立對應的View,這樣其實可以用在多個module依賴的時候,如果在moduleA中得不到moduleB的某個自定義View,可以使用一個這樣的方式來在moudleA中暫時的用來做一個佔位標記,在moduleB中做一個判斷。

同樣的,通過上面的程式碼我們知道LayoutInflater是通過反射拿到構造方法來建立View的,那眾所周知反射是有效能損耗的,那麼我們可以在onCreateView方法中判斷名字直接new出來,當然也可以跟AppcompatActivity裡面做的一樣,做一些相容的操作來替換成不同版本的View:

public final View createView(View parent, final String name, @NonNull Context context,
        View view = null;
        switch (name) {
            case "TextView":
                view = new AppCompatTextView(context, attrs);
                break;
            case "ImageView":
                view = new AppCompatImageView(context, attrs);
                break;
            case "Button":
                view = new AppCompatButton(context, attrs);
                break;
            case "EditText":
                view = new AppCompatEditText(context, attrs);
                break;
            case "Spinner":
                view = new AppCompatSpinner(context, attrs);
                break;
            case "ImageButton":
                view = new AppCompatImageButton(context, attrs);
                break;
            ...
        }
...
        return view;
    }

還沒有展開說rinflate,篇幅限制,放到另外一篇文章中去分析,rinflate原始碼分析

流程圖如下:

總結

  • LayoutInfalter的作用是把XML轉化成對應的View物件,需要用Activity#getLayoutInflater()或者getSystemService獲取
  • 載入時先判斷是否是merge標籤,merge標籤走遞迴方法rinflate,否則走createViewFromTag
  • createViewFromTag作用是根據xml標籤的名字去載入對應的View,使用的是反射的方法
  • LayoutInflater.Factory2是設計出來靈活構造View的介面,可以用來實現換膚或者替換View的功能,同時也是AppcompatActivity用來做相容和版本替換的介面

以上就是原始碼分析Android LayoutInflater的使用的詳細內容,更多關於Android LayoutInflater的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com