换肤流程

首先实现插件式换肤需要知道以下几个流程:

  • 在默认情况下通过 setContentView 设置的资源布局(XML)是如何加载到界面上的
  • 在 Android 5.0 之前的版本和 5.0 之后的版本按钮是不一样的样式,系统是如何做到换肤的
  • 自定义换肤框架,如何知道我们自己的 APK 哪些控件是需要换肤的
  • 如何切换 【皮肤插件 / 默认】的肤色
  • 如何加载资源包插件
  • 重启 APP、进入其他 Activty 如何换肤

setContentView 源码分析

我们都知道我们在 Activity 中是通过 setContentView 来设置一个布局资源,最终会显示到界面上的,那么先看下这个 xml 是如何解析加载到布局上的,假设这里我们继承的是 Activity

1
2
3
4
5
6
7
8
// 继承的是 **Activity**
public class Main2Activity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
    }
}

最终会调用到 Activity#setContentView 方法

1
2
3
4
public void setContentView(@LayoutRes int layoutResID) {
    getWindow().setContentView(layoutResID);
    initWindowDecorActionBar();
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
/**
 * Abstract base class for a top-level window look and behavior policy.  An
 * instance of this class should be used as the top-level view added to the
 * window manager. It provides standard UI policies such as a background, title
 * area, default key processing, etc.
 *
 * <p>The only existing implementation of this abstract class is
 * android.view.PhoneWindow, which you should instantiate when needing a
 * Window.
 */
public abstract class Window {

通过 getWindow() 获取了一个 window,这个 window 其实就是 PhoneWindow ,源码中就只有这一个实现,可以看源码的注释有这个说明,然后就会在 PhoneWindow 中调用的 setContentView

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Override
public void setContentView(int layoutResID) {
    if (mContentParent == null) {
        installDecor();
    } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
        mContentParent.removeAllViews();
    }

    if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
        final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                getContext());
        transitionTo(newScene);
    } else {
        mLayoutInflater.inflate(layoutResID, mContentParent);
    }
    mContentParent.requestApplyInsets();
    final Callback cb = getCallback();
    if (cb != null && !isDestroyed()) {
        cb.onContentChanged();
    }
    mContentParentExplicitlySet = true;
}

XML 布局解析

上面部分比较重要的地方就是 installDecor 方法,和第 14 行的 mLayoutInflater.inflate(layoutResID, mContentParent); 方法。

其中 installDecor 内部就是创建了 decorView,然后加载了一个系统样式主题的布局,然后再返回了一个 mContentParent 。然后才会通过 mLayoutInflater.inflate(layoutResID, mContentParent); 方法解析我们的 xml 布局,最终加载到 mContentParent 上,所以我们的 xml 布局也就是在 mLayoutInflater.inflate 这个方法中进行解析的了,看看都做了什么:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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 {
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    if (root != null) {
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            temp.setLayoutParams(params);
                        }
                    }
                    rInflateChildren(parser, temp, attrs, true);

                    // to root. Do that now.
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

            } catch (XmlPullParserException e) {
             		 // ... 
            }

            return result;
        }
}

我们通常是这么调用的,有 3 个参数,如下:

1
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)

那这几个参数有什么区别呢,在使用上,总是会模糊不清到底要不要传入 root,attachToRoot 到底是传入 true 还是 false ,那么这 3 个参数的区别就在上面源码部分完全体现了,总结如下:

  • resource 不为 null,root 为 null ,attachToRoot 为 [false/true]
    • 直接将 resource 转换成一个 View ,将其返回,并无其他操作
  • resource 不为 null,root 不为 null ,attachToRoot 为 false
    • 会获取 root ViewGroup 布局的 LayoutParams 参数,将 resource 转换成 View 后设置为 root 获取的 LayoutParams
  • resource 不为 null,root 不为 null ,attachToRoot 为 true
    • 会将 resource 转换成 View 后,将这个 View 作为子 View 添加到 root 中,并设置为 root 的 LayoutParams 参数

这 3 个参数的区别就是这些,刚才我们说到 resource 会转换成一个 View ,然后将其返回。到这里还是没发现 XML 是在哪里解析的,那么 XML 又是在哪里解析的呢 ?其实他就是通过上面的 createViewFromTag 内部进行解析的,看如下源码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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.
        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,也就是 XML 定义的 xxx.xxx.xxxView  
                        view = onCreateView(parent, name, attrs);
                    } else {
                      	// 解析系统的布局,会自己拼装 android.view.xxxView
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }

            return view;
        } catch (InflateException e) {
            // .... 
    }

最终调用就是这个地方了,并返回了一个 View ,其中最重要的地方是这个方法 mFactory2.onCreateView() ,这个地方目前默认为空,也就是要收集我们解析的 xml 的 View ,就需要通过这个方法。接下来我们看看 Android 5.0 以上的很多控件都是 MD 风格的,看看系统是如何做的。

注意:假设这个时候我们继承的是 AppCompatActivity ,来看看做了什么,有什么区别:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    final AppCompatDelegate delegate = getDelegate();
    delegate.installViewFactory();
    delegate.onCreate(savedInstanceState);
    if (delegate.applyDayNight() && mThemeId != 0) {
        // If DayNight has been applied, we need to re-apply the theme for
        // the changes to take effect. On API 23+, we should bypass
        // setTheme(), which will no-op if the theme ID is identical to the
        // current theme ID.
        if (Build.VERSION.SDK_INT >= 23) {
            onApplyThemeResource(getTheme(), mThemeId, false);
        } else {
            setTheme(mThemeId);
        }
    }
    super.onCreate(savedInstanceState);
}

可以看到这里在 super.onCreate 方法前面,调用了 installViewFactory 和 onCreate ,看看这个干了什么,其中这里的 getDelegate 如果你看继承体现的话,最终会发现这个实现是在 AppCompatDelegateImplV9 中

AppCompatDelegateImplV9#installViewFactory

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@Override
public void installViewFactory() {
    LayoutInflater layoutInflater = LayoutInflater.from(mContext);
    if (layoutInflater.getFactory() == null) {
        LayoutInflaterCompat.setFactory2(layoutInflater, this);
    } else {
        if (!(layoutInflater.getFactory2() instanceof AppCompatDelegateImplV9)) {
            Log.i(TAG, "The Activity's LayoutInflater already has a Factory installed"
                    + " so we can not install AppCompat's");
        }
    }
}

可以看到这里设置了一个 setFactory2 ,也就是刚才我们分析的继承自 Activity 的时候,这个是为空的,那么继承自 AppCompatActivity 这个时候就不为空了,而且是在 Super.onCreate 方法之前设置的。以刚才分析的流程那么还是会经过 createViewFromTag 方法,然后这个时候 mFactory2 就不为空了,然后就会调用 mFactory2.onCreateView 方法了, 这个方法的实现也是在 AppCompatDelegateImplV9 类中,看看做了什么:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
    @Override
    public View createView(View parent, final String name, @NonNull Context context,
            @NonNull AttributeSet attrs) {
       
				// 省略部分代码,最终会调用 mAppCompatViewInflater.createView 方法
        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 */
        );
    }

然后这里最终会调用 mAppCompatViewInflater.createView 方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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;

    View view = null;
    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;
    }
    return view;
}

可以看到这里 case 中,对很多控件名称做了判断,来看看一个基础的 textView 的 case 中:

1
2
3
4
@NonNull
protected AppCompatTextView createTextView(Context context, AttributeSet attrs) {
    return new AppCompatTextView(context, attrs);
}

可以看到创建了一个 AppCompatTextView 进行返回,到这里就可以发现在 Android 5.0 以上,会设置一个 mFactory2 ,然后就可以拦截到 View 的创建流程了,5.0 之上都返回了带 AppCompatXXX 的一些兼容 View。这也是造成 MD 风格的原因之一,也即是系统在这个部分是如何做到换肤的

这里需要注意的是,到这里我们已经知道了系统是如何拦截 View 的创建流程了,那么如果是我们自己实现插件式换肤的话,那么这个时候我们需要加载的是一个外部的资源包,并不像系统那样已经内嵌在 APK 里面了,同时换肤的话,一般也就是 setBackground,setColor,setXXX 等等方法,所以这里我们需要考虑的问题有:

  • 资源如何加载
  • 设置资源

资源加载

我们都知道,平常我们都是使用 context.getResources().getDrawable(resId) 这样来获取资源 Id 的, 那我们就以这个为例子,看看是如何获取资源的

1
2
3
4
5
6
7
8
9
public Drawable getDrawable(@DrawableRes int id) throws NotFoundException {
    final Drawable d = getDrawable(id, null);
    if (d != null && d.canApplyTheme()) {
        Log.w(TAG, "Drawable " + getResourceName(id) + " has unresolved theme "
                + "attributes! Consider using Resources.getDrawable(int, Theme) or "
                + "Context.getDrawable(int).", new RuntimeException());
    }
    return d;
}

继续看 getDrawable(id, null); 方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public Drawable getDrawable(@DrawableRes int id, @Nullable Theme theme)
        throws NotFoundException {
    final TypedValue value = obtainTempTypedValue();
    try {
        final ResourcesImpl impl = mResourcesImpl;
        impl.getValue(id, value, true);
        return impl.loadDrawable(this, value, id, theme, true);
    } finally {
        releaseTempTypedValue(value);
    }
}

这里可以发现使用的是 mResourcesImpl 这个实现类,最终通过这个实现类调用 loadDrawable 加载资源 id,那么我们再看看 mResourcesImpl 在哪里创建的:

1
2
3
4
public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config) {
    this(null);
    mResourcesImpl = new ResourcesImpl(assets, metrics, config, new DisplayAdjustments());
}

这里可以看到传入了一个 AssetManager ,其中 AssetManager 就是用来提供资源包路径的,所以我们这里就是要创建我们自己的 Resources 然后设置我们自己的资源包路径的 AssetManager 即可,不过需要注意的是,由于设置路径的 addAssetPath 方法是 hide 的,所以需要反射。关于反射设置包路径,和获取资源信息,这里就直接提供下代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
public class SkinResource {
    // 获取资源
    private Resources mResources;

    private String mPackageName;


    public SkinResource(Context context, String skinPath) {
        try {
            AssetManager assetManager = AssetManager.class.newInstance();
            // assetManager 最重要的是要添加 path 路径
            Method addPathMethod = AssetManager.class.getDeclaredMethod("addAssetPath", String.class);
            addPathMethod.setAccessible(true);

            // addAssetPath 注入皮肤包
            addPathMethod.invoke(assetManager, skinPath);

            // 获取内存中已经在运行的 对象
            Resources superResource = context.getResources();

            mResources = new Resources(assetManager,
                    superResource.getDisplayMetrics(), superResource.getConfiguration());

            // 获取skinPath 路径下的包名
            mPackageName = context.getPackageManager().getPackageArchiveInfo(skinPath, PackageManager.GET_ACTIVITIES)
                    .packageName;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过设置资源的名称获取drawable drawable="名称"
     */
    public Drawable getDrawableByResName(String resName) {
        int resId;
        try {
            resId = mResources.getIdentifier(resName, "mipmap", mPackageName);
            return mResources.getDrawable(resId);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                resId = mResources.getIdentifier(resName, "drawable", mPackageName);
                return mResources.getDrawable(resId);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            return null;
        }

    }

    /**
     * 通过设置资源的名称获取颜色 color="名称"
     */
    public ColorStateList getColorByResName(String resName) {
        try {
            int resId = mResources.getIdentifier(resName, "color", mPackageName);
            return mResources.getColorStateList(resId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

源码

好了,到这里就差不多结束了,我们换肤需要 Hook 部分就是这些流程了,这里提供下源码:github.com/midFang/EasyJoke 详细部分可以看下源码实现,这里再说明一下源码中实践的一些大体流程:

  1. 配置资源包路径,如果没有资源则使用默认的皮肤
  2. 在 super.onCreate 之前设置我们自己的 LayoutInflater.Factory
  3. 拦截系统创建 View 的流程(需要兼容 Android 5.0 的 MD 效果)
  4. 收集 Activity 中的需要切换皮肤的 View,解析 View 和记录属性值(可自定义是否切换皮肤属性例如: isChangeSkin,自定义 View 配置接口等)
  5. 默认检测是否需要切换皮肤 (保证重启 APP,进入其他 Activity 可以加载皮肤)
  6. 切换皮肤(通过我们自己的设置过皮肤路径的 Resources 类来获取资源 id,需要传入 package)

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    
    public Drawable getDrawableByResName(String resName) {
    int resId;
    try {
      	// mResources 拥有插件包的路径信息,mPackageName 传入的是插件包的名称
        resId = mResources.getIdentifier(resName, "mipmap", mPackageName);
        return mResources.getDrawable(resId);
    } catch (Exception e) {
        e.printStackTrace();
        try {
            resId = mResources.getIdentifier(resName, "drawable", mPackageName);
            return mResources.getDrawable(resId);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return null;
    }
    }
  7. 可配置一个 skinModule 来专门配置我们的皮肤插件,该 module 并没有类信息,只有皮肤资源,最终生成一个皮肤 APK 提供给主 APK 使用,需要注意的是这个 skinModule 的版本信息最好和主 APK 的版本信息一致