主题包我想大家项目中都有用到,而且谷歌官方也给出了内置的暗黑模式的处理,但是今天要讲的是动态配置主题包,可配置图片,背景色,字体等等......
1. 项目需求
- 根据配置更改不同的主题色,比如背景色,字体颜色。
2. 源码流程解析
切入点:分析源码我们可以知道
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.(当我们inflate解析布局的时候,我们可以通过此类实现hook每一个控件,并且自定义设置他们的属性)
大致翻译应该是这个意思吧,哈哈哈,英语不好。那我们知道要想改变控件属性,必须和这个接口相关,而这个接口只有个方法,方法名称和参数也可以看得出来加载布局的时候每一个控件都会被此方法拦截到。然而他还有一个继承类Factory2
可以看出Factory2
其实是Factory
的扩展。
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.
*
*
* 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
布局加载到手机上可见的。
进入源码我们可以发现以下代码:
1. 分析界面加载控件过程,找寻和我们切入点相关的地方
@Override
public void setContentView(int resId) {
//获取主题TypeArray,判断当前window设置,比如是否全屏,主题模式等等,最终创建出窗口decorView,包括状态栏,navagation栏,content区域,整个窗口布局的规划
//这也就解释了为什么我们设置状态栏一体化之类的需要在setContentView之前做。
ensureSubDecor();
//窗口获取我们的根布局android.R.id.content,也就是开发者布局的区域
ViewGroup contentParent = mSubDecor.findViewById(android.R.id.content);
//清空操作,就想你每次吃饭的时候都要再擦一下筷子一样,明明洗过了。(我是这样理解的哈)
contentParent.removeAllViews();
//解析我们的xml布局
LayoutInflater.from(mContext).inflate(resId, contentParent);
//屏幕刷新回调
mAppCompatWindowCallback.getWrapped().onContentChanged();
}
接下来LayoutInflater.from(mContext).inflate(resId, contentParent);
分析:
- 首先,这段代码会把我们的
resId
文件转换成XmlResourceParser
解析类 - 并且,
XmlResourceParser
类会去读取我们xml
布局的节点 - 再次,把读取出来的每个节点的信息
name
,attributes
通过createViewFromTag()
方法创建出每一个控件对象(比如:name:TextView, attributes:{android:layout_width,android:layout_height,android:text,android:textColor}
等),分析只对一般情况解析,不解析特殊情况,特殊标签(比如:merge
,include
等) - 接下来我们就可以在上面方法中看到我们的切入点:
//此方法四步拦截,Factory2,Factory,mPrivateFactory,LayoutInflater自己处理
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
// ............
View view;
//可以看出,我们创建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;
//..............
分析到这里就够了,因为我们已经找到了我们的切入点和view创建的关系,他能够在每个控件创建的过程中拦截到他们的所有属性,接下来我们对界面加载的分析到此为止。
2. 找寻Factory和Factory2的实例化具体位置
- 显然,
Factory2
是在serContentView()
之前实例化的,所以就针对serContentView()
之前的系统操作查看源码,最终我们再super.onCreate()
中找到这样代码:
AppCompatDelegateImpl.java
@Override
public void installViewFactory() {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
//从这里可以看到,如果我们的Factory为null,系统会给我创建设置一个,这个设置的就是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
主题,创建AppCompatViewInflater
对象,然后又把创建view的任务交给它处理。不难理解,这整个操作就是做我们的兼容包里面的控件处理,也就是说当我们用兼容控件的时候也正常创建我们的控件(比如:AppCompatButton
,Button
)。解析来在进入源码,就可以看到我们兼容的时候的兼容控件和我们原生控件的对应创建关系:
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
创建过程中会经过Factory
的拦截操作,拦截之后兼容包的处理方式是创建兼容的AppcompatInflater
,然后交由它去根据name
对应创建兼容的控件。回头看看AppcompatInflater
是public
的,我们的activity实现了Factory2接口.......
思路:我们根据上面分析,我们的思路就有了,我们可以模范系统对兼容包的处理方式,自定义CustomInflater
继承AppcompatInflater
,拦截每个控件,通过name
匹配,创建我们自己的自定义控件CustomButton
(当然我们的自定义控件也应该是继承系统的控件,比如CustomButton
继承AppcompatButton
,直接继承兼容包的就可以了,因为我们也要为它做兼容,此处要注意一点,我们的继承父类最好是相关的控件的最终子类,比如:「Button
--->AppcomatButton
--->MaterialButton
---CustomButton
」,只有在继承体系里面的才能被支持,否知的话不支持。)