本文基于SDK 28, android studio 4.1.1

1、样式定义以及使用

1.1、默认样式

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

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.example.myapplication">
  4. <application
  5. android:allowBackup="true"
  6. android:icon="@mipmap/ic_launcher"
  7. android:label="@string/app_name"
  8. android:roundIcon="@mipmap/ic_launcher_round"
  9. android:supportsRtl="true"
  10. android:theme="@style/Theme.MyApplication"
  11. >
  12. <activity
  13. android:name=".MainActivity"
  14. android:label="@string/app_name">
  15. <intent-filter>
  16. <action android:name="android.intent.action.MAIN" />
  17. <category android:name="android.intent.category.LAUNCHER" />
  18. </intent-filter>
  19. </activity>
  20. </application>
  21. </manifest>

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

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

  1. <resources xmlns:tools="http://schemas.android.com/tools">
  2. <!-- Base application theme. -->
  3. <style name="Theme.MyApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
  4. <!-- Primary brand color. -->
  5. <item name="colorPrimary">@color/purple_500</item>
  6. <item name="colorPrimaryVariant">@color/purple_700</item>
  7. <item name="colorOnPrimary">@color/white1</item>
  8. <!-- Secondary brand color. -->
  9. <item name="colorSecondary">@color/teal_200</item>
  10. <item name="colorSecondaryVariant">@color/teal_700</item>
  11. <item name="colorOnSecondary">@color/black1</item>
  12. <!-- Status bar color. -->
  13. <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
  14. <!-- Customize your theme here. -->
  15. </style>
  16. </resources>

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

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

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

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

1.2、样式定义及使用

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

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <attr name="color_background" format="color" />
  4. </resources>

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

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. ...
  4. <style name="activity_theme" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
  5. <item name="color_background">#FFAAAAAA</item>
  6. </style>
  7. ...
  8. </resources>

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

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

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

  1. @Override
  2. protected void onCreate(Bundle savedInstanceState) {
  3. setTheme(R.style.activity_theme);
  4. super.onCreate(savedInstanceState);
  5. setContentView(R.layout.activity_main);
  6. }

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

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

当前样式下color_background属性可以通过TypedValue来获取:

  1. TypedValue typedValue = new TypedValue();
  2. MainActivity.this.getTheme().resolveAttribute(R.attr.color_background, typedValue, true);
  3. Log.d("MainActivity", "R.attr.color_background属性:" + typedValue.coerceToString());

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

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

  1. <resources>
  2. ...
  3. <declare-styleable name="custom">
  4. <attr name="string1" format="string" />
  5. <attr name="color1" format="color" />
  6. </declare-styleable>
  7. ...
  8. </resources>

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

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

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

  1. int[] attrs = R.styleable.custom;
  2. TypedArray array = MainActivity.this.getTheme().obtainStyledAttributes(attrs);
  3. for (int i = 0; i < array.getIndexCount(); i++) {
  4. int attr = array.getIndex(i);
  5. if (attr == R.styleable.custom_string1) {
  6. String string1 = array.getString(attr);
  7. Log.d("MainActivity", "R.styleable.custom_string1属性: " + string1);
  8. } else if (attr == R.styleable.custom_color1) {
  9. int color1 = array.getColor(attr, Color.BLACK);
  10. Log.d("MainActivity", "R.styleable.custom_color1属性: #" + Integer.toHexString(color1));
  11. }
  12. }

2、Activity中Theme的初始化流程

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

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

​ 在MainActivity中重写setTheme, 并增加断点, 启动调试,则可获得如下调用堆栈:



​ 点到上一步performLaunchActivity:



ActivityInfo类型的变量r.activityInfo的getThemeResource()方法如下:

  1. public final int getThemeResource() {
  2. return theme != 0 ? theme : applicationInfo.theme;
  3. }

​ 表示:如果当前activity有对应的theme,就设置,否则就使用application的theme,这两个theme分别设置在activity标签和application标签下。

​ setTheme代码如下:

  1. @Override
  2. public void setTheme(int resid) {
  3. if (mThemeResource != resid) {
  4. mThemeResource = resid;
  5. initializeTheme();
  6. }
  7. }
  8. private void initializeTheme() {
  9. final boolean first = mTheme == null;
  10. if (first) {
  11. mTheme = getResources().newTheme();
  12. final Resources.Theme theme = getBaseContext().getTheme();
  13. if (theme != null) {
  14. mTheme.setTo(theme);
  15. }
  16. }
  17. onApplyThemeResource(mTheme, mThemeResource, first);
  18. }
  19. protected void onApplyThemeResource(Resources.Theme theme, int resId, boolean first) {
  20. theme.applyStyle(resId, true);
  21. }

​ 首先判断设置的resId和mThemeResource是不是一样,如果不一样就对mThemeResource赋值,检查并初始化mTheme,然后调用Resources.Theme#applyStyle方法 --> ResourceImpl.ThemeImpl#applyStyle

  1. void applyStyle(int resId, boolean force) {
  2. synchronized (mKey) {
  3. mAssets.applyStyleToTheme(mTheme, resId, force);
  4. mThemeResId = resId;
  5. mKey.append(resId, force);
  6. }
  7. }

​ mAssets类型为AssetManager,applyStyleToTheme方法调用native方法nativeThemeApplyStyle,这个方法将样式中的属性键值对复制到mTheme中,这一过程类似于Map的put方法,存在就更新,不存在就存入。再创建一个样式activity_theme1, color_background属性定义为#ffffff, 可通过如下代码验证:

  1. setTheme(R.style.activity_theme);
  2. context.getTheme().resolveAttribute(R.attr.color_background, typedValue, true);
  3. Log.d("MainActivity", "R.attr.color_background属性:" + typedValue.coerceToString());
  4. setTheme(R.style.activity_theme1);
  5. context.getTheme().resolveAttribute(R.attr.color_background, typedValue, true);
  6. Log.d("MainActivity", "R.attr.color_background属性:" + typedValue.coerceToString());
  7. int[] attrs = R.styleable.custom;
  8. //string1和color1还是activity_theme样式中定义的值
  9. TypedArray array = context.getTheme().obtainStyledAttributes(attrs);
  10. for (int i = 0; i < array.getIndexCount(); i++) {
  11. int attr = array.getIndex(i);
  12. if (attr == R.styleable.custom_string1) {
  13. String string1 = array.getString(attr);
  14. Log.d("MainActivity", "R.styleable.custom_string1属性: " + string1);
  15. } else if (attr == R.styleable.custom_color1) {
  16. int color1 = array.getColor(attr, Color.BLACK);
  17. Log.d("MainActivity", "R.styleable.custom_color1属性: #" + Integer.toHexString(color1));
  18. }
  19. }

​ 如果将application标签下的android:theme="@style/Theme.MyApplication"移除,程序依旧可以运行,再将activity_theme中的 parent="Theme.MaterialComponents.DayNight.DarkActionBar"去掉,运行程序,程序就会报异常:

AppCompatDelegateImpl类中异常抛出的代码如下:

  1. private ViewGroup createSubDecor() {
  2. TypedArray a = mContext.obtainStyledAttributes(R.styleable.AppCompatTheme);
  3. if (!a.hasValue(R.styleable.AppCompatTheme_windowActionBar)) {
  4. a.recycle();
  5. throw new IllegalStateException(
  6. "You need to use a Theme.AppCompat theme (or descendant) with this activity.");
  7. }
  8. ...
  9. return subDecor;
  10. }

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

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

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

  1. ```
  2. setTheme(R.style.Theme_MaterialComponents_DayNight_DarkActionBar);
  3. setTheme(R.style.activity_theme);
  4. ```

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

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

2.2、getTheme()逻辑

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

  1. @Override
  2. public Resources.Theme getTheme() {
  3. if (mTheme != null) {
  4. return mTheme;
  5. }
  6. mThemeResource = Resources.selectDefaultTheme(mThemeResource,
  7. getApplicationInfo().targetSdkVersion);
  8. initializeTheme();
  9. return mTheme;
  10. }

​ 主要逻辑是:如果mTheme已经初始化过,就返回mTheme,如果没有,就调用Resources.selectDefaultTheme,根据mThemeResource和sdk版本号选择对应的样式id(mThemeResource不为0就返回mThemeResource),通过initializeTheme初始化mTheme。

3、定义特殊需求的样式

​ 定义一个Toast的样式:

  1. <style name="toast_theme">
  2. <item name="color_background">#ff0000</item>
  3. </style>

​ 如果需要获取该样式下的属性值,可以通过构建Context来完成。一般地,可以通过如下代码来获取该样式下的属性值:

  1. ContextThemeWrapper contextThemeWrapper = new ContextThemeWrapper(getApplication(), R.style.activity_theme);
  2. TypedValue typedValue = new TypedValue();
  3. contextThemeWrapper.getTheme().resolveAttribute(R.attr.color_background, typedValue, true);
  4. Log.d("Test", typedValue.coerceToString().toString());

​ 以上构建的contextThemeWrapper可以用来加载View、显示Toast等(Activity实际上就是一个ContextThemeWrapper)。Toast也可以保存下来复用,改变文字、字体颜色、背景等等,它实际引用的是Application,不会造成内存泄露。

  1. Toast toast = new Toast(contextThemeWrapper);
  2. View contentView = LayoutInflater.from(contextThemeWrapper).inflate(R.layout.toast_text, null);
  3. TextView textView = (TextView) contentView;
  4. textView.setText("Hello, World!");
  5. toast.setView(contentView);
  6. toast.show();

​ 其中R.layout.toast_text如下:

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

​ Application也可以通过调用setTheme来赋予其一些属性值,它继承自ContextWrapper, 内部的mBase是android.app.ContextImpl的实例, android.app.ContextImpl#setTheme实现了和android.view.ContextThemeWrapper#setTheme同样的逻辑,可以用于加载View、显示Toast等等。

  1. Application application = getApplication();
  2. application.setTheme(R.style.toast_theme);
  3. Toast toast = new Toast(application);
  4. View contentView = LayoutInflater.from(application).inflate(R.layout.toast_text, null);
  5. TextView textView = (TextView) contentView;
  6. textView.setText("Hello, World!");
  7. toast.setView(contentView);
  8. 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. Codeforces Round #672 (Div. 2 B. Rock and Lever (位运算)

    题意:给你一组数,求有多少对\((i,j)\),使得\(a_{i}\)&\(a_{j}\ge a_{i}\ xor\ a_{j}\). 题解:对于任意两个数的二进制来说,他们的最高位要么相同要 ...

  2. Codeforces Round #650 (Div. 3) E. Necklace Assembly (暴力)

    题意:有一个字符串,要求使用其中字符构造一个环(不必全部都用),定义一个环是k美的,如果它转\(k\)次仍是原样,现在给你\(k\),要求最长的k美环的长度. 题解:我们首先看\(k\),如果一个环转 ...

  3. cs寄存器

    练习 答案: 代码段: cs:ip指定的cpu认为是指令

  4. AWS注册到连接

    1. 注册AWS账号 https://www.cnblogs.com/cmt/p/13912814.html 2.注册完成之后,选择实例 Ubuntu,下载xxx.pem文件,查看实例得到ip 比如我 ...

  5. Kafka官方文档V2.7

    1.开始 1.1 简介 什么是事件流? 事件流相当于人体的中枢神经系统的数字化.它是 "永远在线 "世界的技术基础,在这个世界里,业务越来越多地被软件定义和自动化,软件的用户更是软 ...

  6. HDU 6623 Minimal Power of Prime(思维)题解

    题意: 已知任意大于\(1\)的整数\(a = p_1^{q_1}p_2^{q_2} \cdots p_k^{q_k}\),现给出\(a \in [2,1e18]\),求\(min\{q_i\},q ...

  7. μC/OS-III---I笔记10---内存管理

    内存管理: 平时经常用到一些windows内存管理的软件,有一些内存管理的软件进行内存碎片的整理,在频繁分配和释放内存的地方会造成大量的内存碎片.内存碎片是如何形成的呢?书中是这样写的:在不断的分配和 ...

  8. 数仓增量更新hive实现

    注:参考文末文章,加上自己的理解. 1.增量更新 有一个 base_table 表存放的是 12 月 15 日之前的所有数据,当 12 月 16 日的数据产生后,生成了一个 incremental_t ...

  9. Vue2.0 多种组件传值方法-不过如此的 Vuex

    码文不易啊,转载请带上本文链接呀,感谢感谢 https://www.cnblogs.com/echoyya/p/14404397.html 在vue项目中了解组件间通讯很重要,也是最基础的面试题,可以 ...

  10. Pygame 游戏开发 All In One

    Pygame 游戏开发 All In One Pygame Pygame is a library for digital arts, games, music, making, and a comm ...