本文共 7714 字,大约阅读时间需要 25 分钟。
本文基于SDK 28, android studio 4.1.1
创建一个简单的项目, 其AndroidManifest.xml配置如下:
其中android:theme指定应用的样式Theme.MyApplication, 在values和values-night文件夹的themes.xml中定义,分别表示白色模式和暗黑模式。
values文件夹下themes.xml定义如下:
Theme.MyApplication样式继承自Theme.materialComponents.DayNight.DarkActionBar, 定义了白色风格下状态栏颜色、背景色等;同样地,values-night文件夹下themes.xml中Theme.MyApplication定义了黑色风格下状态栏颜色、背景色等。
转到colorPrimary定义(Ctrl + 鼠标左键),在appcompat-xxx下的values.xml中定义如下:
... ...
可以看出colorPrimary是一个attr属性,其在两个Theme.MyApplication样式中都设置了值。
在某些情况下针对具体的Activity,需要处理特殊样式,仿照着Theme.MyApplication创建Activity的样式。在values文件夹下创建attrs.xml。在attrs.xml中定义attr类型的背景颜色
分别在values和values-night文件夹下的theme.xml中定义activity的样式activity_theme, 并分别定义color_background为#FFAAAAAA、#FF333333
... ...
在布局文件中引用该属性作为背景:
...
在Activity加载View之前设置MainActivity的样式:
@Overrideprotected void onCreate(Bundle savedInstanceState) { setTheme(R.style.activity_theme); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);}
运行程序,就可以看到activity_theme中定义的color_background =#FFAAAAAA背景色效果。
当前样式下color_background属性可以通过TypedValue来获取:
TypedValue typedValue = new TypedValue(); MainActivity.this.getTheme().resolveAttribute(R.attr.color_background, typedValue, true); Log.d("MainActivity", "R.attr.color_background属性:" + typedValue.coerceToString());
在values.xml中定义属性集合custom:
... ...
在activity_theme样式中添加对应属性
可通过如下代码获取对应属性:
int[] attrs = R.styleable.custom;TypedArray array = MainActivity.this.getTheme().obtainStyledAttributes(attrs);for (int i = 0; i < array.getIndexCount(); i++) { int attr = array.getIndex(i); if (attr == R.styleable.custom_string1) { String string1 = array.getString(attr); Log.d("MainActivity", "R.styleable.custom_string1属性: " + string1); } else if (attr == R.styleable.custom_color1) { int color1 = array.getColor(attr, Color.BLACK); Log.d("MainActivity", "R.styleable.custom_color1属性: #" + Integer.toHexString(color1)); }}
Activity中主题设置方法为setTheme,获取主题方法为getTheme,下面分别分析setTheme和getTheme()
在MainActivity中重写setTheme, 并增加断点, 启动调试,则可获得如下调用堆栈:
点到上一步performLaunchActivity:ActivityInfo类型的变量r.activityInfo的getThemeResource()方法如下:public final int getThemeResource() { return theme != 0 ? theme : applicationInfo.theme;}
表示:如果当前activity有对应的theme,就设置,否则就使用application的theme,这两个theme分别设置在activity标签和application标签下。
setTheme代码如下:
@Overridepublic void setTheme(int resid) { if (mThemeResource != resid) { mThemeResource = resid; initializeTheme(); }}private void initializeTheme() { final boolean first = mTheme == null; if (first) { mTheme = getResources().newTheme(); final Resources.Theme theme = getBaseContext().getTheme(); if (theme != null) { mTheme.setTo(theme); } } onApplyThemeResource(mTheme, mThemeResource, first);}protected void onApplyThemeResource(Resources.Theme theme, int resId, boolean first) { theme.applyStyle(resId, true);}
首先判断设置的resId和mThemeResource是不是一样,如果不一样就对mThemeResource赋值,检查并初始化mTheme,然后调用Resources.Theme#applyStyle方法 --> ResourceImpl.ThemeImpl#applyStyle
void applyStyle(int resId, boolean force) { synchronized (mKey) { mAssets.applyStyleToTheme(mTheme, resId, force); mThemeResId = resId; mKey.append(resId, force); }}
mAssets类型为AssetManager,applyStyleToTheme方法调用native方法nativeThemeApplyStyle,这个方法将样式中的属性键值对复制到mTheme中,这一过程类似于Map的put方法,存在就更新,不存在就存入。再创建一个样式activity_theme1, color_background属性定义为#ffffff, 可通过如下代码验证:
setTheme(R.style.activity_theme);context.getTheme().resolveAttribute(R.attr.color_background, typedValue, true);Log.d("MainActivity", "R.attr.color_background属性:" + typedValue.coerceToString());setTheme(R.style.activity_theme1);context.getTheme().resolveAttribute(R.attr.color_background, typedValue, true);Log.d("MainActivity", "R.attr.color_background属性:" + typedValue.coerceToString());int[] attrs = R.styleable.custom;//string1和color1还是activity_theme样式中定义的值TypedArray array = context.getTheme().obtainStyledAttributes(attrs);for (int i = 0; i < array.getIndexCount(); i++) { int attr = array.getIndex(i); if (attr == R.styleable.custom_string1) { String string1 = array.getString(attr); Log.d("MainActivity", "R.styleable.custom_string1属性: " + string1); } else if (attr == R.styleable.custom_color1) { int color1 = array.getColor(attr, Color.BLACK); Log.d("MainActivity", "R.styleable.custom_color1属性: #" + Integer.toHexString(color1)); }}
如果将application标签下的android:theme="@style/Theme.MyApplication"移除,程序依旧可以运行,再将activity_theme中的 parent="Theme.MaterialComponents.DayNight.DarkActionBar"去掉,运行程序,程序就会报异常:
AppCompatDelegateImpl类中异常抛出的代码如下:
private ViewGroup createSubDecor() { TypedArray a = mContext.obtainStyledAttributes(R.styleable.AppCompatTheme); if (!a.hasValue(R.styleable.AppCompatTheme_windowActionBar)) { a.recycle(); throw new IllegalStateException( "You need to use a Theme.AppCompat theme (or descendant) with this activity."); } ... return subDecor;}
这就是样式继承的意义所在:提供一些默认的属性。
以上样式继承在效果上等价于activity_theme去掉parent,然后代码中先后调用
```setTheme(R.style.Theme_MaterialComponents_DayNight_DarkActionBar);setTheme(R.style.activity_theme); ```
如果想要改变一些属性,如状态栏颜色,可以在对应样式中进行修改:
Activity的getTheme方法来自于android.view.ContextThemeWrapper类,代码如下:
@Overridepublic Resources.Theme getTheme() { if (mTheme != null) { return mTheme; } mThemeResource = Resources.selectDefaultTheme(mThemeResource, getApplicationInfo().targetSdkVersion); initializeTheme(); return mTheme;}
主要逻辑是:如果mTheme已经初始化过,就返回mTheme,如果没有,就调用Resources.selectDefaultTheme,根据mThemeResource和sdk版本号选择对应的样式id(mThemeResource不为0就返回mThemeResource),通过initializeTheme初始化mTheme。
定义一个Toast的样式:
如果需要获取该样式下的属性值,可以通过构建Context来完成。一般地,可以通过如下代码来获取该样式下的属性值:
ContextThemeWrapper contextThemeWrapper = new ContextThemeWrapper(getApplication(), R.style.activity_theme);TypedValue typedValue = new TypedValue();contextThemeWrapper.getTheme().resolveAttribute(R.attr.color_background, typedValue, true);Log.d("Test", typedValue.coerceToString().toString());
以上构建的contextThemeWrapper可以用来加载View、显示Toast等(Activity实际上就是一个ContextThemeWrapper)。Toast也可以保存下来复用,改变文字、字体颜色、背景等等,它实际引用的是Application,不会造成内存泄露。
Toast toast = new Toast(contextThemeWrapper);View contentView = LayoutInflater.from(contextThemeWrapper).inflate(R.layout.toast_text, null);TextView textView = (TextView) contentView;textView.setText("Hello, World!");toast.setView(contentView);toast.show();
其中R.layout.toast_text如下:
Application也可以通过调用setTheme来赋予其一些属性值,它继承自ContextWrapper, 内部的mBase是android.app.ContextImpl的实例, android.app.ContextImpl#setTheme实现了和android.view.ContextThemeWrapper#setTheme同样的逻辑,可以用于加载View、显示Toast等等。
Application application = getApplication();application.setTheme(R.style.toast_theme);Toast toast = new Toast(application);View contentView = LayoutInflater.from(application).inflate(R.layout.toast_text, null);TextView textView = (TextView) contentView;textView.setText("Hello, World!");toast.setView(contentView);toast.show();
(1) AndroidManifest.xml中activity标签下android:theme优先级更高,application标签下的android:theme次之,直接在代码中设置setTheme优先级最高。对Activity,系统默认设置AndroidManifest.xml中配置的theme;对Application, 系统没有设置过主题。
(2) 样式类似于Map,key是attr的id值,value是对应的属性值,可以进行继承、覆盖等。
转载地址:http://cudbz.baihongyu.com/