欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

源碼分析Android?LayoutInflater的使用

 更新時(shí)間:2023年04月19日 11:33:37   作者:Yocn  
簡(jiǎn)單來(lái)說(shuō),LayoutInflater的工作就是將使用xml文件編寫(xiě)的布局轉(zhuǎn)換成Android里的View對(duì)象,并且這也是Android中將xml布局轉(zhuǎn)換成View的唯一方式。本文將從源碼帶大家了解一下LayoutInflater的具體使用

LayoutInflater

開(kāi)頭先附一段LayoutInflater類的注釋簡(jiǎn)介

/**
 * 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開(kāi)頭的一段介紹,我們能看到幾個(gè)重要的信息:

  • LayoutInfalter的作用是把XML轉(zhuǎn)化成對(duì)應(yīng)的View對(duì)象,需要用Activity#getLayoutInflater()或者getSystemService獲取,會(huì)綁定當(dāng)前的Context
  • 如果需要使用自定義的Factory查看替換加載信息,需要用cloneInContext去克隆一個(gè)ViewFactory,然后調(diào)用setFactory設(shè)置自定義的Factory
  • 性能原因,inflate會(huì)在build階段進(jìn)行,無(wú)法用來(lái)加載一個(gè)外部文本XML文件,只能加載R.xxx.xxx這種處理好的資源文件。
//LayoutInflater.java
    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
	//root是否為null來(lái)決定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();
        }
    }
//三個(gè)inflate方法最終都會(huì)調(diào)用到下面這個(gè)三個(gè)參數(shù)的inflate方法。
    /**
     * parser XML節(jié)點(diǎn)包含了View的層級(jí)描述
     * root 需要attached到的根目錄,如果attachToRoot為true則root必須不為null。
     * attachToRoot 加載的層級(jí)是否需要attach到rootView,
     * return attachToRoot為true,就返回root,反之false就返回加載的XML文件的根節(jié)點(diǎn)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文件,并根據(jù)得到的標(biāo)簽名執(zhí)行不同的邏輯:

  • 首先如果是merge標(biāo)簽,會(huì)走rInflate方法,方法前面帶r的說(shuō)明是recurse遞歸方法
  • 如果不是merge標(biāo)簽,執(zhí)行createViewFromTag,根據(jù)傳入的nameattrs獲取到name對(duì)應(yīng)的rootView并且添加到root里面。

針對(duì)merge標(biāo)簽,如果是merge標(biāo)簽必須有root并且必須attachToRoot==true,否則直接拋異常,所以我們得知merge必須作為root標(biāo)簽使用,并且不能用在子標(biāo)簽中①,rInflate方法中也會(huì)針對(duì)merge標(biāo)簽進(jìn)行檢查,保證merge標(biāo)簽不會(huì)出現(xiàn)在子標(biāo)簽中,后面會(huì)有介紹。
檢查通過(guò)則調(diào)用rInflate(parser, root, inflaterContext, attrs, false)方法,遞歸遍歷root的層級(jí),解析加載childrenView掛載到parentView下面,rinflate詳細(xì)解析可以看rinflate

如果不是merge標(biāo)簽則調(diào)用createViewFromTag(root, name, inflaterContext, attrs),這個(gè)方法的作用是加載名字為name的view,根據(jù)name反射方式創(chuàng)建對(duì)應(yīng)的View,根據(jù)傳入的attrs構(gòu)造Params設(shè)置給View,返回創(chuàng)建好的View。
當(dāng)然這只是創(chuàng)建了一個(gè)View,需要再調(diào)用rInflateChildren(parser, temp, attrs, true),這個(gè)方法也是一個(gè)遞歸方法,它的作用是根據(jù)傳入的parser包含的層級(jí),加載此層級(jí)的子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) {
            ...
        }
    }

先看當(dāng)前標(biāo)簽的attr屬性里面是否設(shè)置了theme,如果設(shè)置了就用當(dāng)前標(biāo)簽的theme屬性,綁定到context上面。 這里很有意思的是特殊判斷了一個(gè)TAG_1995,也就是blink,一個(gè)將包裹的內(nèi)容每隔500ms顯示隱藏的一個(gè)標(biāo)簽,怎么看都像個(gè)彩蛋~

然后調(diào)用mFactory2onCreateView,如果沒(méi)有設(shè)置mFactory2就嘗試mFactory,否則調(diào)用mPrivateFactory,mFactory2和mFactory后面再說(shuō),這里先往后走。

如果還是沒(méi)有加載到view,先判斷name,看名字里是不是有.,如果沒(méi)有就表明是Android原生的View,最終都會(huì)調(diào)用到createView方法,onCreateView最終會(huì)調(diào)用到createView(name, "android.view.", attrs);,會(huì)在View名字天面添加"android.view."前綴。

下面是默認(rèn)的createView的實(shí)現(xiàn):

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

這個(gè)方法可以看到View是怎么創(chuàng)建出來(lái)的,用類的全限定名拿到class信息,有一個(gè)sConstructorMap緩存類的constructor,如果能拿到有效的構(gòu)造器就不再重復(fù)創(chuàng)建來(lái)提升效率,如果沒(méi)有緩存的構(gòu)造器,就反射得到構(gòu)造器并添加到sConstructorMap中以便后面使用。這里有個(gè)mFilter來(lái)提供自定義選項(xiàng),用戶可以自定義哪些類不允許構(gòu)造。

拿到構(gòu)造器之后,實(shí)際上newInstance是調(diào)用了兩View個(gè)參數(shù)的構(gòu)造方法。第一個(gè)參數(shù)是Context,第二個(gè)參數(shù)是attrs,這樣我們就得到了需要加載的View。

這里可以結(jié)合LayoutInflater.Factory2一起來(lái)看,Activity實(shí)際上是實(shí)現(xiàn)了LayoutInflater.Factory2接口的:

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

所以我們可以直接在Activity里面重寫(xiě)onCreateView方法,這樣就可以根據(jù)View的名字來(lái)實(shí)現(xiàn)我們的一些操作,比如換膚的操作,比如定義一個(gè)名字來(lái)表示某種自定義View??梢钥催@樣一個(gè)用法:

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

然后我們?cè)谥貙?xiě)的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);
    }

這樣其實(shí)就不拘泥于名字可以自己創(chuàng)建對(duì)應(yīng)的View,這樣其實(shí)可以用在多個(gè)module依賴的時(shí)候,如果在moduleA中得不到moduleB的某個(gè)自定義View,可以使用一個(gè)這樣的方式來(lái)在moudleA中暫時(shí)的用來(lái)做一個(gè)占位標(biāo)記,在moduleB中做一個(gè)判斷。

同樣的,通過(guò)上面的代碼我們知道LayoutInflater是通過(guò)反射拿到構(gòu)造方法來(lái)創(chuàng)建View的,那眾所周知反射是有性能損耗的,那么我們可以在onCreateView方法中判斷名字直接new出來(lái),當(dāng)然也可以跟AppcompatActivity里面做的一樣,做一些兼容的操作來(lái)替換成不同版本的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;
    }

還沒(méi)有展開(kāi)說(shuō)rinflate,篇幅限制,放到另外一篇文章中去分析,rinflate源碼分析

流程圖如下:

總結(jié)

  • LayoutInfalter的作用是把XML轉(zhuǎn)化成對(duì)應(yīng)的View對(duì)象,需要用Activity#getLayoutInflater()或者getSystemService獲取
  • 加載時(shí)先判斷是否是merge標(biāo)簽,merge標(biāo)簽走遞歸方法rinflate,否則走createViewFromTag
  • createViewFromTag作用是根據(jù)xml標(biāo)簽的名字去加載對(duì)應(yīng)的View,使用的是反射的方法
  • LayoutInflater.Factory2是設(shè)計(jì)出來(lái)靈活構(gòu)造View的接口,可以用來(lái)實(shí)現(xiàn)換膚或者替換View的功能,同時(shí)也是AppcompatActivity用來(lái)做兼容和版本替換的接口

以上就是源碼分析Android LayoutInflater的使用的詳細(xì)內(nèi)容,更多關(guān)于Android LayoutInflater的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論