溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android?LayoutInflater怎么使用

發(fā)布時間:2023-04-19 14:24:40 來源:億速云 閱讀:94 作者:iii 欄目:開發(fā)技術

本篇內容介紹了“Android LayoutInflater怎么使用”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!

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方法最終都會調用到下面這個三個參數(shù)的inflate方法。
    /**
     * parser XML節(jié)點包含了View的層級描述
     * root 需要attached到的根目錄,如果attachToRoot為true則root必須不為null。
     * attachToRoot 加載的層級是否需要attach到rootView,
     * return attachToRoot為true,就返回root,反之false就返回加載的XML文件的根節(jié)點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ù)得到的標簽名執(zhí)行不同的邏輯:

  • 首先如果是merge標簽,會走rInflate方法,方法前面帶r的說明是recurse遞歸方法

  • 如果不是merge標簽,執(zhí)行createViewFromTag,根據(jù)傳入的nameattrs獲取到name對應的rootView并且添加到root里面。

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

如果不是merge標簽則調用createViewFromTag(root, name, inflaterContext, attrs),這個方法的作用是加載名字為name的view,根據(jù)name反射方式創(chuàng)建對應的View,根據(jù)傳入的attrs構造Params設置給View,返回創(chuàng)建好的View。
當然這只是創(chuàng)建了一個View,需要再調用rInflateChildren(parser, temp, attrs, true),這個方法也是一個遞歸方法,它的作用是根據(jù)傳入的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的實現(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);
        }
    }

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

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

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

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

所以我們可以直接在Activity里面重寫onCreateView方法,這樣就可以根據(jù)View的名字來實現(xiàn)我們的一些操作,比如換膚的操作,比如定義一個名字來表示某種自定義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);
    }

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

同樣的,通過上面的代碼我們知道LayoutInflater是通過反射拿到構造方法來創(chuàng)建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;
    }

流程圖如下:

Android?LayoutInflater怎么使用

“Android LayoutInflater怎么使用”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關的知識可以關注億速云網(wǎng)站,小編將為大家輸出更多高質量的實用文章!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI