本文基于SDK 28, android studio 4.1.1

1、样式定义以及使用

1.1、默认样式

创建一个简单的项目, 其AndroidManifest.xml配置如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication"> <application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyApplication"
> <activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> </application> </manifest>

​ 其中android:theme指定应用的样式Theme.MyApplication, 在values和values-night文件夹的themes.xml中定义,分别表示白色模式和暗黑模式。

values文件夹下themes.xml定义如下:

<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.MyApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white1</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black1</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style> </resources>

​ Theme.MyApplication样式继承自Theme.materialComponents.DayNight.DarkActionBar, 定义了白色风格下状态栏颜色、背景色等;同样地,values-night文件夹下themes.xml中Theme.MyApplication定义了黑色风格下状态栏颜色、背景色等。

​ 转到colorPrimary定义(Ctrl + 鼠标左键),在appcompat-xxx下的values.xml中定义如下:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:ns1="urn:oasis:names:tc:xliff:document:1.2">
... <!-- The primary branding color for the app. By default, this is the color applied to the
action bar background. -->
<attr format="color" name="colorPrimary"/>
...
</resources>

可以看出colorPrimary是一个attr属性,其在两个Theme.MyApplication样式中都设置了值。

1.2、样式定义及使用

​ 在某些情况下针对具体的Activity,需要处理特殊样式,仿照着Theme.MyApplication创建Activity的样式。在values文件夹下创建attrs.xml。在attrs.xml中定义attr类型的背景颜色

<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="color_background" format="color" />
</resources>

​ 分别在values和values-night文件夹下的theme.xml中定义activity的样式activity_theme, 并分别定义color_background为#FFAAAAAA、#FF333333

<?xml version="1.0" encoding="utf-8"?>
<resources>
...
<style name="activity_theme" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<item name="color_background">#FFAAAAAA</item>
</style>
...
</resources>

​ 在布局文件中引用该属性作为背景:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="?attr/color_background"> ... </androidx.constraintlayout.widget.ConstraintLayout>

​ 在Activity加载View之前设置MainActivity的样式:

@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.activity_theme);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

运行程序,就可以看到activity_theme中定义的color_background =#FFAAAAAA背景色效果。

1.3、当前样式下attr属性的获取

当前样式下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());

1.4、属性集合的定义与获取

​ 在values.xml中定义属性集合custom:

<resources>
...
<declare-styleable name="custom">
<attr name="string1" format="string" />
<attr name="color1" format="color" />
</declare-styleable>
...
</resources>

​ 在activity_theme样式中添加对应属性

<style name="activity_theme" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<item name="color_background">#FFAAAAAA</item> <item name="string1">Activity</item>
<item name="color1">#0000ff</item>
</style>

​ 可通过如下代码获取对应属性:

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));
}
}

2、Activity中Theme的初始化流程

​ Activity中主题设置方法为setTheme,获取主题方法为getTheme,下面分别分析setTheme和getTheme()

2.1、系统调用setTheme以及setTheme逻辑

​ 在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代码如下:

@Override
public 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;
}

​ 这就是样式继承的意义所在:提供一些默认的属性

    <style name="activity_theme"parent="Theme.MaterialComponents.DayNight.DarkActionBar">
...
</style>

​ 以上样式继承在效果上等价于activity_theme去掉parent,然后代码中先后调用

       ```
setTheme(R.style.Theme_MaterialComponents_DayNight_DarkActionBar);
setTheme(R.style.activity_theme);
```

如果想要改变一些属性,如状态栏颜色,可以在对应样式中进行修改:

<style name="activity_theme">
...
<item name="android:statusBarColor" tools:targetApi="l">#ff0000</item>
</style>

2.2、getTheme()逻辑

Activity的getTheme方法来自于android.view.ContextThemeWrapper类,代码如下:

@Override
public 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。

3、定义特殊需求的样式

​ 定义一个Toast的样式:

<style name="toast_theme">
<item name="color_background">#ff0000</item>
</style>

​ 如果需要获取该样式下的属性值,可以通过构建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如下:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:textColor="#ffffff"
android:textSize="16sp"
android:background="?attr/color_background"> </TextView>

​ 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是对应的属性值,可以进行继承、覆盖等。

Android中Context样式分析的更多相关文章

  1. android中的样式和主题

    有的时候我们一个页面要用很多个textview,而且这些textview的样式非常相像,这种情况下我们可以把这些样式抽取出来,然后在每个textview中引用即可,这样修改起来也方便. 我们来看一个简 ...

  2. Android中AppWidget的分析与应用:AppWidgetProvider .

    from: http://blog.csdn.net/thl789/article/details/7887968 本文从开发AppWidgetProvider角度出发,看一个AppWidgetPrv ...

  3. Android中Context的总结及其用法

    在android中我们经常遇到这样的情况,在创建一个对象的时候往往需要传递一个this参数,比如:语句 MyView mView = new MyView(this),要求传递一个this参数,这个t ...

  4. Android中Context详解 ---- 你所不知道的Context(转)

    Android中Context详解 ---- 你所不知道的Context(转)                                               本文出处 :http://b ...

  5. Android 中图片压缩分析(上)

    作者: shawnzhao,QQ音乐技术团队一员 一.前言 在 Android 中进行图片压缩是非常常见的开发场景,主要的压缩方法有两种:其一是质量压缩,其二是下采样压缩. 前者是在不改变图片尺寸的情 ...

  6. android中的样式主题和国际化

    一.Android中的样式和主题     1.1样式     样式是作用在控件上的,它是一个包含一个或者多个view控件属性的集合.android style类似网页设计中的css设计思路,可以让设计 ...

  7. Android中Context详解

    大家好,  今天给大家介绍下我们在应用开发中最熟悉而陌生的朋友-----Context类 ,说它熟悉,是应为我们在开发中时刻的在与它打交道,例如:Service.BroadcastReceiver.A ...

  8. Android中Context详解 ---- 你所不知道的Context

    转自:http://blog.csdn.net/qinjuning/article/details/7310620Android中Context详解 ---- 你所不知道的Context 大家好,  ...

  9. 转:Android中Context详解 ---- 你所不知道的Context

    转:http://blog.csdn.net/qinjuning/article/details/7310620 转:http://blog.csdn.net/lmj623565791/article ...

随机推荐

  1. 牛客挑战赛33 C 艾伦的立体机动装置(几何)

    思路: 我们需要枚举展开多少条边 然后把上底面的点放到和下底面一个平面 然后算两点之间的距离 注意判断直线与线段是否有交点 #include <bits/stdc++.h> using n ...

  2. POJ1113:Wall (凸包算法学习)

    题意: 给你一个由n个点构成的多边形城堡(看成二维),按顺序给你n个点,相邻两个点相连. 让你围着这个多边形城堡建一个围墙,城堡任意一点到围墙的距离要求大于等于L,让你求这个围墙的最小周长(看成二维平 ...

  3. 【noi 2.6_9290】&【poj 2680】Computer Transformation(DP+高精度+重载运算符)

    题意:给一个初始值1,每步操作将1替换为01,将0替换为10.问N步操作后有多少对连续的0. 解法:f[i]表示第i步后的答案.可以直接打表发现规律--奇数步后,f[i]=f[i-1]*2-1;偶数步 ...

  4. 关于markdown的入门使用

    关于标题 方式一: 使用 = - 标示一,二级标题 = 表示一级标题 - 表示二级标题 示例: 我展示的是一级标题 ================= 我展示的是二级标题 -------------- ...

  5. kubernetes进阶(五)dashboard--WEB管理

    dashboard是k8s的可视化管理平台,是三种管理k8s集群方法之一 首先下载镜像上传到我们的私有仓库中:hdss7-200 # docker pull k8scn/kubernetes-dash ...

  6. 导出Excel的异常处理

    问题: 提示:"类 Range 的 Select 方法无效" 处理方法: 设置当前工作表 this.worksheet.Activate();

  7. 【非原创】sg函数模板

    学习博客:戳这里 解题模型: 1.把原游戏分解成多个独立的子游戏,则原游戏的SG函数值是它的所有子游戏的SG函数值的异或.        即sg(G)=sg(G1)^sg(G2)^...^sg(Gn) ...

  8. C# wpf window

    使用vs2017 新建wpf 项目 MainWindow 被定义为partial,是因为他要和xaml的一些属性组合在一起,然后再运行起来,这正是 InitailizeCompoent 这个函数要干的 ...

  9. tensorflow-gpu+"Failed to create session"

    成因: 未给系统指定相应使用的GPU 解决: 层面1: 针对单个程序: CUDA_VISIBLE_DEVICES=0 python main.py import os; os.environ['CUD ...

  10. HTML5 drag & drop & H5 DnD

    HTML5 drag & drop H5 DnD https://html5demos.com/ demos https://html5demos.com/dnd-upload https:/ ...