主題包---源碼解析,思路分析

kotlin vs java

主題包我想大家項(xiàng)目中都有用到,而且谷歌官方也給出了內(nèi)置的暗黑模式的處理,但是今天要講的是動態(tài)配置主題包,可配置圖片,背景色,字體等等......

1. 項(xiàng)目需求

  • 根據(jù)配置更改不同的主題色,比如背景色,字體顏色。

2. 源碼流程解析

切入點(diǎn):分析源碼我們可以知道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.(當(dāng)我們inflate解析布局的時候,我們可以通過此類實(shí)現(xiàn)hook每一個控件,并且自定義設(shè)置他們的屬性)大致翻譯應(yīng)該是這個意思吧,哈哈哈,英語不好。那我們知道要想改變控件屬性,必須和這個接口相關(guān),而這個接口只有個方法,方法名稱和參數(shù)也可以看得出來加載布局的時候每一個控件都會被此方法攔截到。然而他還有一個繼承類Factory2可以看出Factory2其實(shí)是Factory的擴(kuò)展。

  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.
         *
         * <p>
         * 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);
    }

接下來我們分析setContentView(layoutId)的時候加載布局頁面的一系列操作,是怎么樣把xml布局加載到手機(jī)上可見的。

進(jìn)入源碼我們可以發(fā)現(xiàn)以下代碼:

1. 分析界面加載控件過程,找尋和我們切入點(diǎn)相關(guān)的地方
 @Override
    public void setContentView(int resId) {
        //獲取主題TypeArray,判斷當(dāng)前window設(shè)置,比如是否全屏,主題模式等等,最終創(chuàng)建出窗口decorView,包括狀態(tài)欄,navagation欄,content區(qū)域,整個窗口布局的規(guī)劃
       //這也就解釋了為什么我們設(shè)置狀態(tài)欄一體化之類的需要在setContentView之前做。
        ensureSubDecor();
        //窗口獲取我們的根布局android.R.id.content,也就是開發(fā)者布局的區(qū)域
        ViewGroup contentParent = mSubDecor.findViewById(android.R.id.content);
        //清空操作,就想你每次吃飯的時候都要再擦一下筷子一樣,明明洗過了。(我是這樣理解的哈)
        contentParent.removeAllViews();
        //解析我們的xml布局
        LayoutInflater.from(mContext).inflate(resId, contentParent);
        //屏幕刷新回調(diào)
        mAppCompatWindowCallback.getWrapped().onContentChanged();
    }

接下來LayoutInflater.from(mContext).inflate(resId, contentParent);分析:

  1. 首先,這段代碼會把我們的resId文件轉(zhuǎn)換成XmlResourceParser解析類
  2. 并且,XmlResourceParser類會去讀取我們xml布局的節(jié)點(diǎn)
  3. 再次,把讀取出來的每個節(jié)點(diǎn)的信息name,attributes通過createViewFromTag()方法創(chuàng)建出每一個控件對象(比如:name:TextView, attributes:{android:layout_width,android:layout_height,android:text,android:textColor}等),分析只對一般情況解析,不解析特殊情況,特殊標(biāo)簽(比如:merge,include等)
  4. 接下來我們就可以在上面方法中看到我們的切入點(diǎn):
    //此方法四步攔截,F(xiàn)actory2,F(xiàn)actory,mPrivateFactory,LayoutInflater自己處理
    View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
           // ............
            View view;
          //可以看出,我們創(chuàng)建view的過程會在這里被Factory和Factory2攔截
            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;
        //..............

分析到這里就夠了,因?yàn)槲覀円呀?jīng)找到了我們的切入點(diǎn)和view創(chuàng)建的關(guān)系,他能夠在每個控件創(chuàng)建的過程中攔截到他們的所有屬性,接下來我們對界面加載的分析到此為止。

2. 找尋Factory和Factory2的實(shí)例化具體位置
  1. 顯然,Factory2是在serContentView()之前實(shí)例化的,所以就針對serContentView()之前的系統(tǒng)操作查看源碼,最終我們再super.onCreate()中找到這樣代碼:
AppCompatDelegateImpl.java
  @Override
    public void installViewFactory() {
        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        //從這里可以看到,如果我們的Factory為null,系統(tǒng)會給我創(chuàng)建設(shè)置一個,這個設(shè)置的就是this,也就是說AppCompatDelegateImpl會攔截到我們所要的所有的控件
        if (layoutInflater.getFactory() == null) {
            LayoutInflaterCompat.setFactory2(layoutInflater, this);
        } else {
            if (!(layoutInflater.getFactory2() instanceof AppCompatDelegateImpl)) {
                Log.i(TAG, "The Activity's LayoutInflater already has a Factory installed"
                        + " so we can not install AppCompat's");
            }
        }
    }

那接下來我們看看AppCompatDelegateImpl.java攔截獲取到我們所有控件后做了什么:

@Override
    public View createView(View parent, final String name, @NonNull Context context,
            @NonNull AttributeSet attrs) {
        if (mAppCompatViewInflater == null) {
            TypedArray a = mContext.obtainStyledAttributes(R.styleable.AppCompatTheme);
            String viewInflaterClassName =
                    a.getString(R.styleable.AppCompatTheme_viewInflaterClass);
            if ((viewInflaterClassName == null)
                    || AppCompatViewInflater.class.getName().equals(viewInflaterClassName)) {
                // Either default class name or set explicitly to null. In both cases
                // create the base inflater (no reflection)
                mAppCompatViewInflater = new AppCompatViewInflater();
            } else {
                try {
                    Class<?> viewInflaterClass = Class.forName(viewInflaterClassName);
                    mAppCompatViewInflater =
                            (AppCompatViewInflater) viewInflaterClass.getDeclaredConstructor()
                                    .newInstance();
                } catch (Throwable t) {
                    Log.i(TAG, "Failed to instantiate custom view inflater "
                            + viewInflaterClassName + ". Falling back to default.", t);
                    mAppCompatViewInflater = new AppCompatViewInflater();
                }
            }
        }

        boolean inheritContext = false;
        if (IS_PRE_LOLLIPOP) {
            inheritContext = (attrs instanceof XmlPullParser)
                    // If we have a XmlPullParser, we can detect where we are in the layout
                    ? ((XmlPullParser) attrs).getDepth() > 1
                    // Otherwise we have to use the old heuristic
                    : shouldInheritContext((ViewParent) parent);
        }

        return mAppCompatViewInflater.createView(parent, name, context, attrs, inheritContext,
                IS_PRE_LOLLIPOP, /* Only read android:theme pre-L (L+ handles this anyway) */
                true, /* Read read app:theme as a fallback at all times for legacy reasons */
                VectorEnabledTintResources.shouldBeUsed() /* Only tint wrap the context if enabled */
        );
    }

可以看到代碼不多,做了一件事兒,就是兼容AppCompat主題,創(chuàng)建AppCompatViewInflater對象,然后又把創(chuàng)建view的任務(wù)交給它處理。不難理解,這整個操作就是做我們的兼容包里面的控件處理,也就是說當(dāng)我們用兼容控件的時候也正常創(chuàng)建我們的控件(比如:AppCompatButton,Button)。解析來在進(jìn)入源碼,就可以看到我們兼容的時候的兼容控件和我們原生控件的對應(yīng)創(chuàng)建關(guān)系:

final View createView(View parent, final String name, @NonNull Context context,
            @NonNull AttributeSet attrs, boolean inheritContext,
            boolean readAndroidTheme, boolean readAppTheme, boolean wrapContext) {
        final Context originalContext = context;

        // We can emulate Lollipop's android:theme attribute propagating down the view hierarchy
        // by using the parent's context
        if (inheritContext && parent != null) {
            context = parent.getContext();
        }
        if (readAndroidTheme || readAppTheme) {
            // We then apply the theme on the context, if specified
            context = themifyContext(context, attrs, readAndroidTheme, readAppTheme);
        }
        if (wrapContext) {
            context = TintContextWrapper.wrap(context);
        }

        View view = null;

        // We need to 'inject' our tint aware Views in place of the standard framework versions
        switch (name) {
            case "TextView":
                view = createTextView(context, attrs);
                verifyNotNull(view, name);
                break;
            case "ImageView":
                view = createImageView(context, attrs);
                verifyNotNull(view, name);
                break;
            case "Button":
                view = createButton(context, attrs);
                verifyNotNull(view, name);
                break;
            case "EditText":
                view = createEditText(context, attrs);
                verifyNotNull(view, name);
                break;
            case "Spinner":
                view = createSpinner(context, attrs);
                verifyNotNull(view, name);
                break;
            case "ImageButton":
                view = createImageButton(context, attrs);
                verifyNotNull(view, name);
                break;
            case "CheckBox":
                view = createCheckBox(context, attrs);
                verifyNotNull(view, name);
                break;
            case "RadioButton":
                view = createRadioButton(context, attrs);
                verifyNotNull(view, name);
                break;
            case "CheckedTextView":
                view = createCheckedTextView(context, attrs);
                verifyNotNull(view, name);
                break;
            case "AutoCompleteTextView":
                view = createAutoCompleteTextView(context, attrs);
                verifyNotNull(view, name);
                break;
            case "MultiAutoCompleteTextView":
                view = createMultiAutoCompleteTextView(context, attrs);
                verifyNotNull(view, name);
                break;
            case "RatingBar":
                view = createRatingBar(context, attrs);
                verifyNotNull(view, name);
                break;
            case "SeekBar":
                view = createSeekBar(context, attrs);
                verifyNotNull(view, name);
                break;
            case "ToggleButton":
                view = createToggleButton(context, attrs);
                verifyNotNull(view, name);
                break;
            default:
                view = createView(context, name, attrs);
        }

        if (view == null && originalContext != context) {
            // If the original context does not equal our themed context, then we need to manually
            // inflate it using the name so that android:theme takes effect.
            view = createViewFromTag(context, name, attrs);
        }

        if (view != null) {
            // If we have created a view, check its android:onClick
            checkOnClickListener(view, attrs);
        }

        return view;
    }

到這里我們梳理一下思路,我們在view創(chuàng)建過程中會經(jīng)過Factory的攔截操作,攔截之后兼容包的處理方式是創(chuàng)建兼容的AppcompatInflater,然后交由它去根據(jù)name對應(yīng)創(chuàng)建兼容的控件?;仡^看看AppcompatInflaterpublic的,我們的activity實(shí)現(xiàn)了Factory2接口.......
思路:我們根據(jù)上面分析,我們的思路就有了,我們可以模范系統(tǒng)對兼容包的處理方式,自定義CustomInflater繼承AppcompatInflater,攔截每個控件,通過name匹配,創(chuàng)建我們自己的自定義控件CustomButton(當(dāng)然我們的自定義控件也應(yīng)該是繼承系統(tǒng)的控件,比如CustomButton繼承AppcompatButton,直接繼承兼容包的就可以了,因?yàn)槲覀円惨獮樗黾嫒荩颂幰⒁庖稽c(diǎn),我們的繼承父類最好是相關(guān)的控件的最終子類,比如:「Button--->AppcomatButton--->MaterialButton---CustomButton」,只有在繼承體系里面的才能被支持,否知的話不支持。)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容