├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── drawable
│ │ │ │ ├── ic_theme_light_24px.xml
│ │ │ │ ├── ic_theme_dark_24px.xml
│ │ │ │ ├── ic_theme_default_24px.xml
│ │ │ │ ├── ic_edge_to_edge_disable_24dp.xml
│ │ │ │ ├── ic_edge_to_edge_enable_24dp.xml
│ │ │ │ └── ic_launcher_background.xml
│ │ │ ├── values
│ │ │ │ ├── colors.xml
│ │ │ │ ├── strings.xml
│ │ │ │ ├── theme.xml
│ │ │ │ ├── theme_overlay_secondary.xml
│ │ │ │ ├── styles.xml
│ │ │ │ ├── arrays.xml
│ │ │ │ └── theme_overlay_primary.xml
│ │ │ ├── values-night
│ │ │ │ └── theme.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── layout
│ │ │ │ └── activity_main.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── flywith24
│ │ │ │ └── theme_demo
│ │ │ │ ├── Theme.kt
│ │ │ │ ├── ThemeViewModel.kt
│ │ │ │ ├── WindowPreFerencesManager.kt
│ │ │ │ └── MainActivity.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── flywith24
│ │ │ └── theme_demo
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── flywith24
│ │ └── theme_demo
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradle.properties
├── gradlew.bat
├── gradlew
└── README.md
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 | rootProject.name = "Flywith24-Theme-demo"
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Flywith24/Flywith24-Theme-demo/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Flywith24/Flywith24-Theme-demo/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Flywith24/Flywith24-Theme-demo/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Flywith24/Flywith24-Theme-demo/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Flywith24/Flywith24-Theme-demo/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Flywith24/Flywith24-Theme-demo/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Flywith24/Flywith24-Theme-demo/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Flywith24/Flywith24-Theme-demo/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Flywith24/Flywith24-Theme-demo/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Flywith24/Flywith24-Theme-demo/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Flywith24/Flywith24-Theme-demo/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Jun 22 13:58:46 CST 2020
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/java/com/flywith24/theme_demo/Theme.kt:
--------------------------------------------------------------------------------
1 | package com.flywith24.theme_demo
2 |
3 | import androidx.appcompat.app.AppCompatDelegate
4 |
5 | /**
6 | * @author Flywith24
7 | * @date 2020/6/24
8 | * time 10:02
9 | * description
10 | */
11 | enum class Theme(val mode: Int) {
12 | LIGHT(AppCompatDelegate.MODE_NIGHT_NO),
13 | DARK(AppCompatDelegate.MODE_NIGHT_YES),
14 | SYSTEM(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
15 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/flywith24/theme_demo/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.flywith24.theme_demo
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_theme_light_24px.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_theme_dark_24px.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_theme_default_24px.xml:
--------------------------------------------------------------------------------
1 |
7 |
10 |
--------------------------------------------------------------------------------
/app/src/main/java/com/flywith24/theme_demo/ThemeViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.flywith24.theme_demo
2 |
3 | import androidx.annotation.StyleRes
4 | import androidx.lifecycle.MutableLiveData
5 | import androidx.lifecycle.ViewModel
6 |
7 | /**
8 | * @author Flywith24
9 | * @date 2020/6/23
10 | * time 19:13
11 | * description
12 | */
13 | class ThemeViewModel : ViewModel() {
14 | val primaryColor = MutableLiveData<@StyleRes Int>()
15 | val currentTheme = MutableLiveData(Theme.SYSTEM)
16 | val edgeToEdgeEnabled = MutableLiveData(false)
17 |
18 | fun setCurrentTheme(theme: Theme) {
19 | //防抖
20 | if (theme == currentTheme.value) return
21 | currentTheme.value = theme
22 | }
23 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 | #9C27B0
8 | #673AB7
9 | #4A148C
10 | #311B92
11 | #26A69A
12 | #1B5E20
13 | #ffffff
14 | #FF9800
15 | #D84315
16 | #FF9E80
17 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/flywith24/theme_demo/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.flywith24.theme_demo
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.flywith24.theme_demo", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_edge_to_edge_disable_24dp.xml:
--------------------------------------------------------------------------------
1 |
16 |
22 |
25 |
26 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Theme-demo
3 | Light
4 | Dark
5 | System Default
6 | 普通 button
7 | 设置style
8 | 设置theme
9 | theme overlay
10 | 这是个文本,颜色为 \n?android:attr/textColorPrimary\n可以跟随主题变化颜色
11 | 这是个文本,颜色为 \n?attr/colorPrimary\n可以跟随 theme overlay colorPrimary 变化颜色
12 |
13 | Red
14 | Purple
15 | Indigo
16 | Blue
17 | Green
18 | Yellow
19 | Orange
20 | Brown
21 | Grey
22 | Blue grey
23 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_edge_to_edge_enable_24dp.xml:
--------------------------------------------------------------------------------
1 |
16 |
22 |
25 |
26 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
--------------------------------------------------------------------------------
/app/src/main/res/values/theme.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
14 |
15 |
21 |
22 |
31 |
--------------------------------------------------------------------------------
/app/src/main/res/values-night/theme.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
14 |
15 |
21 |
22 |
31 |
--------------------------------------------------------------------------------
/app/src/main/res/values/theme_overlay_secondary.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
11 |
12 |
15 |
16 |
19 |
20 |
23 |
24 |
27 |
28 |
31 |
32 |
35 |
36 |
39 |
40 |
43 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-android-extensions'
4 |
5 | android {
6 | compileSdkVersion 29
7 | buildToolsVersion "29.0.3"
8 |
9 | defaultConfig {
10 | applicationId "com.flywith24.theme_demo"
11 | minSdkVersion 23
12 | targetSdkVersion 29
13 | versionCode 1
14 | versionName "1.0"
15 |
16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
17 | }
18 |
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 | kotlinOptions {
26 | jvmTarget = "1.8"
27 | }
28 | }
29 |
30 | dependencies {
31 | implementation fileTree(dir: "libs", include: ["*.jar"])
32 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
33 | implementation 'androidx.core:core-ktx:1.3.0'
34 | implementation 'androidx.appcompat:appcompat:1.1.0'
35 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
36 | testImplementation 'junit:junit:4.12'
37 | androidTestImplementation 'androidx.test.ext:junit:1.1.1'
38 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
39 | implementation "com.google.android.material:material:1.3.0-alpha01"
40 | implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.3.0-alpha04"
41 | implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0-alpha04"
42 | implementation "androidx.fragment:fragment-ktx:1.3.0-alpha06"
43 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
15 |
16 |
20 |
21 |
31 |
32 |
38 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/res/values/arrays.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | - @style/ThemeOverlay.PrimaryPalette.Red
5 | - @style/ThemeOverlay.PrimaryPalette.Purple
6 | - @style/ThemeOverlay.PrimaryPalette.Indigo
7 | - @style/ThemeOverlay.PrimaryPalette.Blue
8 | - @style/ThemeOverlay.PrimaryPalette.Green
9 | - @style/ThemeOverlay.PrimaryPalette.Yellow
10 | - @style/ThemeOverlay.PrimaryPalette.Orange
11 | - @style/ThemeOverlay.PrimaryPalette.Brown
12 | - @style/ThemeOverlay.PrimaryPalette.Grey
13 | - @style/ThemeOverlay.PrimaryPalette.BlueGrey
14 |
15 |
16 |
17 | - @style/ThemeOverlay.SecondaryPalette.Red
18 | - @style/ThemeOverlay.SecondaryPalette.Purple
19 | - @style/ThemeOverlay.SecondaryPalette.Indigo
20 | - @style/ThemeOverlay.SecondaryPalette.Blue
21 | - @style/ThemeOverlay.SecondaryPalette.Green
22 | - @style/ThemeOverlay.SecondaryPalette.Yellow
23 | - @style/ThemeOverlay.SecondaryPalette.Orange
24 | - @style/ThemeOverlay.SecondaryPalette.Brown
25 | - @style/ThemeOverlay.SecondaryPalette.Grey
26 | - @style/ThemeOverlay.SecondaryPalette.BlueGrey
27 |
28 |
29 |
30 | - @string/hint_red
31 | - @string/hint_purple
32 | - @string/hint_indigo
33 | - @string/hint_blue
34 | - @string/hint_green
35 | - @string/hint_yellow
36 | - @string/hint_orange
37 | - @string/hint_brown
38 | - @string/hint_grey
39 | - @string/hint_blue_grey
40 |
41 |
--------------------------------------------------------------------------------
/app/src/main/res/values/theme_overlay_primary.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
8 |
9 |
13 |
14 |
18 |
19 |
23 |
24 |
28 |
29 |
33 |
34 |
38 |
39 |
43 |
44 |
48 |
49 |
53 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/app/src/main/java/com/flywith24/theme_demo/WindowPreFerencesManager.kt:
--------------------------------------------------------------------------------
1 | package com.flywith24.theme_demo
2 |
3 | import android.annotation.SuppressLint
4 | import android.content.Context
5 | import android.graphics.Color
6 | import android.graphics.Color.TRANSPARENT
7 | import android.os.Build.VERSION.SDK_INT
8 | import android.os.Build.VERSION_CODES.*
9 | import android.view.View
10 | import androidx.annotation.ColorInt
11 | import androidx.appcompat.app.AppCompatActivity
12 | import androidx.core.graphics.ColorUtils
13 | import com.google.android.material.color.MaterialColors
14 |
15 | /**
16 | * @author Flywith24
17 | * @date 2020/6/24
18 | * time 9:17
19 | * description
20 | */
21 |
22 | private const val EDGE_TO_EDGE_BAR_ALPHA = 128
23 | private const val EDGE_TO_EDGE_FLAGS =
24 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
25 |
26 | /**
27 | * 设置是否全屏(状态栏和导航栏不占空间)
28 | */
29 | @SuppressLint("ObsoleteSdkInt")
30 | fun AppCompatActivity.applyEdgeToEdgePreference(edgeToEdgeEnabled: Boolean) {
31 | if (SDK_INT < LOLLIPOP) return
32 | val statusBarColor = getStatusBarColor(edgeToEdgeEnabled, this)
33 | val navBarColor = getNavBarColor(edgeToEdgeEnabled, this)
34 |
35 | val lightBackground =
36 | isColorLight(MaterialColors.getColor(this, android.R.attr.colorBackground, Color.BLACK))
37 | val lightNavBar = isColorLight(navBarColor)
38 | val showDarkNavBarIcons =
39 | lightNavBar || navBarColor == TRANSPARENT && lightBackground
40 |
41 | with(window) {
42 | val currentStatusBar =
43 | if (SDK_INT >= M) decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR else 0
44 | val currentNavBar =
45 | if (showDarkNavBarIcons && SDK_INT >= O) View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR else 0
46 |
47 | this.navigationBarColor = navBarColor
48 | this.statusBarColor = statusBarColor
49 | val systemUiVisibility =
50 | ((if (edgeToEdgeEnabled) EDGE_TO_EDGE_FLAGS else View.SYSTEM_UI_FLAG_VISIBLE)
51 | or currentStatusBar
52 | or currentNavBar)
53 |
54 | decorView.systemUiVisibility = systemUiVisibility
55 | }
56 | }
57 |
58 | /**
59 | * 获取状态栏颜色
60 | */
61 | @SuppressLint("ObsoleteSdkInt")
62 | fun getStatusBarColor(edgeToEdgeEnabled: Boolean, context: Context): Int = when {
63 | //低版本
64 | edgeToEdgeEnabled && SDK_INT < M -> {
65 | val opaqueStatusBarColor =
66 | MaterialColors.getColor(context, android.R.attr.statusBarColor, Color.BLACK)
67 | ColorUtils.setAlphaComponent(opaqueStatusBarColor, EDGE_TO_EDGE_BAR_ALPHA)
68 | }
69 | edgeToEdgeEnabled -> TRANSPARENT
70 | else -> MaterialColors.getColor(context, android.R.attr.statusBarColor, Color.BLACK)
71 | }
72 |
73 | /**
74 | * 获取导航栏颜色
75 | */
76 | fun getNavBarColor(edgeToEdgeEnabled: Boolean, context: Context): Int = when {
77 | //低版本
78 | edgeToEdgeEnabled && SDK_INT < O_MR1 -> {
79 | val opaqueStatusBarColor =
80 | MaterialColors.getColor(context, android.R.attr.navigationBarColor, Color.BLACK)
81 | ColorUtils.setAlphaComponent(opaqueStatusBarColor, EDGE_TO_EDGE_BAR_ALPHA)
82 | }
83 | edgeToEdgeEnabled -> TRANSPARENT
84 | else -> MaterialColors.getColor(context, android.R.attr.navigationBarColor, Color.BLACK)
85 | }
86 |
87 | fun isColorLight(@ColorInt color: Int): Boolean {
88 | return color != TRANSPARENT && ColorUtils.calculateLuminance(color) > 0.5
89 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/flywith24/theme_demo/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.flywith24.theme_demo
2 |
3 | import android.content.res.ColorStateList
4 | import android.graphics.Color
5 | import android.os.Bundle
6 | import androidx.activity.viewModels
7 | import androidx.annotation.StyleableRes
8 | import androidx.appcompat.app.AppCompatActivity
9 | import androidx.appcompat.widget.AppCompatRadioButton
10 | import androidx.core.widget.CompoundButtonCompat
11 | import androidx.lifecycle.observe
12 | import kotlinx.android.synthetic.main.activity_main.*
13 |
14 | class MainActivity : AppCompatActivity(R.layout.activity_main) {
15 | private val mThemeViewModel by viewModels()
16 |
17 | override fun onCreate(savedInstanceState: Bundle?) {
18 | //配置 primaryColor 是否全屏,在配置布局之前
19 | with(mThemeViewModel) {
20 | primaryColor.value?.let { setTheme(it) }
21 | edgeToEdgeEnabled.value?.let { applyEdgeToEdgePreference(it) }
22 | }
23 |
24 | super.onCreate(savedInstanceState)
25 |
26 | initPrimaryRadioButton()
27 | initToolbar()
28 |
29 | mThemeViewModel.currentTheme.observe(this) { delegate.localNightMode = it.mode }
30 |
31 | initThemeRadioButton()
32 | }
33 |
34 | private fun initThemeRadioButton() {
35 | rgTheme.check(getThemeCheckId())
36 | rgTheme.setOnCheckedChangeListener { _, checkedId ->
37 | when (checkedId) {
38 | R.id.themeLight -> mThemeViewModel.setCurrentTheme(Theme.LIGHT)
39 | R.id.themeDark -> mThemeViewModel.setCurrentTheme(Theme.DARK)
40 | R.id.themeDefault -> mThemeViewModel.setCurrentTheme(Theme.SYSTEM)
41 | }
42 | }
43 | }
44 |
45 | /**
46 | * 根据 mThemeViewModel.currentTheme 选中默认的 theme radio button
47 | */
48 | private fun getThemeCheckId(): Int {
49 | return when (mThemeViewModel.currentTheme.value) {
50 | Theme.LIGHT -> R.id.themeLight
51 | Theme.DARK -> R.id.themeDark
52 | Theme.SYSTEM -> R.id.themeDefault
53 | else -> -1
54 | }
55 | }
56 |
57 | private fun initToolbar() {
58 | val edgeToEdgeEnabled = mThemeViewModel.edgeToEdgeEnabled.value ?: false
59 | toolbar1.setNavigationIcon(if (edgeToEdgeEnabled) R.drawable.ic_edge_to_edge_disable_24dp else R.drawable.ic_edge_to_edge_enable_24dp)
60 | toolbar1.setNavigationOnClickListener {
61 | mThemeViewModel.edgeToEdgeEnabled.value = !edgeToEdgeEnabled
62 | recreate()
63 | }
64 | }
65 |
66 | private fun initPrimaryRadioButton() {
67 | createPrimaryButton()
68 | rgPrimary.setOnCheckedChangeListener { group, checkedId ->
69 | mThemeViewModel.primaryColor.value =
70 | group.findViewById(checkedId).tag as Int
71 | recreate()
72 | }
73 | }
74 |
75 |
76 | private fun createPrimaryButton() {
77 | val primaryArray = resources.obtainTypedArray(R.array.primary_palettes)
78 | val descriptionArray = resources.obtainTypedArray(R.array.palettes_content_description)
79 | var style: Int
80 | if (primaryArray.length() != descriptionArray.length()) {
81 | throw IllegalArgumentException("primary_palettes 与 palettes_content_description 长度不等!")
82 | }
83 | for (index in 0 until primaryArray.length()) {
84 | style = primaryArray.getResourceId(index, 0)
85 | rgPrimary.addView(AppCompatRadioButton(this).apply {
86 | text = descriptionArray.getString(index)
87 | val a = obtainStyledAttributes(style, PRIMARY_THEME_OVERLAY_ATTRS)
88 | CompoundButtonCompat.setButtonTintList(
89 | this, ColorStateList.valueOf(a.getColor(0, Color.TRANSPARENT))
90 | )
91 | // 与 mThemeViewModel.primaryColor 一致则选中
92 | isChecked = mThemeViewModel.primaryColor.value == style
93 | tag = style
94 | a.recycle()
95 | })
96 | }
97 | primaryArray.recycle()
98 | descriptionArray.recycle()
99 | }
100 |
101 | companion object {
102 |
103 | @StyleableRes
104 | private val PRIMARY_THEME_OVERLAY_ATTRS = intArrayOf(
105 | R.attr.colorPrimary, R.attr.colorPrimaryDark
106 | )
107 | }
108 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
19 |
20 |
30 |
31 |
39 |
40 |
47 |
48 |
55 |
56 |
63 |
64 |
65 |
66 |
76 |
77 |
82 |
83 |
84 |
92 |
93 |
100 |
101 |
111 |
112 |
122 |
123 |
130 |
131 |
138 |
139 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## 前言
2 |
3 | 作为 Android 开发者,不知你是否也有这样的体验,随着项目变得越来越大,各种不同圆角的 shape,不同透明度的 color,不同大小的阴影效果,它们使资源文件越来越多
4 |
5 | 我认为造成这种问题的原因有两个:一个是产品设计的不规范,整个 app 没有统一的设计风格;第二个便是开发者在开发过程中编码的不规范
6 |
7 |
8 |
9 | Android Dev Summit '19 有一场关于 Style 与 Theme 的演讲,它的 [中文字幕视频在这里](https://www.bilibili.com/video/BV1uJ411h7jh)
10 |
11 | 我为你整理了每个主题所在的位置
12 |
13 | | **时间** | **内容** |
14 | | :------: | :--------------: |
15 | | 02:14 | Styling vs Theme |
16 | | 08:55 | Theme Overlay |
17 | | 12:36 | Color |
18 | | 17:35 | 使用及三个技巧 |
19 | | 24:00 | Material 颜色 |
20 | | 28:06 | Material 排版 |
21 | | 30:07 | Material 形状 |
22 | | 34:41 | Dark Theme |
23 |
24 | 在视频下方的评论区,点击相应时间即可跳转到指定内容
25 |
26 | 
27 |
28 | 与之对应的有一个 Styling 的系列文章,我最近翻译成了中文
29 |
30 | - [【译】Android Styling 1: Themes vs Styles](https://juejin.im/post/5eead9196fb9a058734e3b03)
31 |
32 |
33 | - [【译】Android Styling 2: 常用主题属性](https://juejin.im/post/5eec07416fb9a058835d0306)
34 |
35 |
36 | - [【译】Android Styling 3: 使用主题和主题属性的优势](https://juejin.im/post/5eed67b4f265da02a642bd57)
37 |
38 |
39 | - [【译】Android Styling 4: 主题实战](https://juejin.im/post/5eeff86cf265da02e8177eba)
40 |
41 |
42 |
43 | 本文整理了视频与文章中的内容,介绍在开发过程中,我们应如何利用 theme 与 style 更优雅地管理资源文件,并提供了很多实用的技巧,在标题中找到技巧相关的查看即可
44 |
45 | 并且提供了演示 demo,效果如下
46 |
47 | 
48 |
49 |
50 |
51 | ## 理解 Style 与 Theme 的区别
52 |
53 | 这部分内容在视频的 02.14 处
54 |
55 | Style 是 View 属性的集合,可以将 Style 视为 Map<**View** Attribute, Resource>,其中 key 为 View 的属性,value 为资源
56 |
57 |
58 |
59 | 
60 |
61 | 
62 |
63 | Resource 可以为以下类型
64 |
65 | 
66 |
67 |
68 |
69 | 而 Theme 则不同,它的 key 是 「主题属性」,很显然下图中的 colorPrimary 不是任何 View 中的属性
70 |
71 | 
72 |
73 | 主题属性有点像把配置抽象为语义化的命名的变量,并把它们塞到 map 中,以便未来使用,主题属性 与 View 属性很像,它们在 attr 中定义的方式以及对应的类型都是类似的,但二者仍有差异
74 |
75 | 
76 |
77 |
78 |
79 | 在引用主题属性时,可以使用 `?.attr` 语法,其中 ?代表在当前主题中搜索
80 |
81 | 
82 |
83 |
84 |
85 | ### 主题属性带来的优势
86 |
87 | 如果我们 app 需要支持普通版本和 Pro 版本,它们的主色不同,我们只需定义两个主题,配置不同的 colorPrimary。接着我们需要适配深色主题,那么只需提供不同的数值即可
88 |
89 | 
90 |
91 | 
92 |
93 | 
94 |
95 |
96 |
97 | 这就好比我们有一个 Theme 抽象类,而其中有一个抽象属性 colorPrimary,它有四个实现类,分别重写了 colorPrimary 属性,这样我们便得到了 四个变体,未来想加入新的变体,只需继承该抽象类并重写属性即可。看过 [第一篇译文](https://juejin.im/post/5eead9196fb9a058734e3b03#heading-6) 的小伙伴知道,主题的作用范围是 「树」中的所有子节点。这样我们便很轻松地实现了更改程序主色的功能
98 |
99 |
100 |
101 | 如果要使用 Style 实现这一功能,首先,我们需要定义四种 Style。由于 Style 的作用范围是特定 View,因此我们要为每个 View 均定义四套 Style
102 |
103 |
104 |
105 | 
106 |
107 |
108 |
109 | ### 小结
110 |
111 | 简单来说,Style 与 Theme 的作用范围不同
112 |
113 |
114 |
115 | Style 只会作用于单一的 View 中,使用时用 `style` 标签
116 |
117 | 
118 |
119 |
120 |
121 | Theme 会作用于「树」中的所有子节点,使用时用 `theme` 标签
122 |
123 | 
124 |
125 |
126 |
127 | 在任意时刻,程序都是运行在某一特定主题下的,例如 activity 被设置了特定主题
128 |
129 | 
130 |
131 |
132 |
133 | 我们在使用时应该注意 theme 与 style 各自的优势,灵活运用二者
134 |
135 |
136 |
137 | ## Theme Overlay
138 |
139 | 这部分内容在视频的 08.55 处
140 |
141 |
142 |
143 | 主题是有继承关系的,当该继承关系链中有多个主题配置了同一属性,那么最继承链最底部的内容会生效,在下图中,如果多个主题都声明了 colorPrimary,那么 Theme.Owl.Pink 中的内容会生效(这有点像 Java 的继承关系)
144 |
145 | 
146 |
147 |
148 |
149 | 利用这种继承关系我们可以实现在粉色主题下将部分界面使用蓝色主题
150 |
151 |
152 |
153 | 
154 |
155 |
156 |
157 | 
158 |
159 |
160 |
161 | 我们看一下两种主题的继承关系,这两种主题的父级应该是比较相似的,这看起来比较浪费,因为很多属性是相同的
162 |
163 | 
164 |
165 | 另外,当你把一个主题设置在另一个主题之上,你需要注意不能将自己想要保留的东西被覆盖掉
166 |
167 |
168 |
169 | `Theme Overlay` 可以很好地解决这一问题,它并不是一项新技术,而是属于一种技巧
170 |
171 | 
172 |
173 | 接下来我们只需关注想要更改的东西,应用下图的声明的主题,则会只改变 colorPrimary 和 colorSecondary 两项属性的值,而其它的所有属性均不变
174 |
175 | 
176 |
177 | ### 技巧1:反转颜色
178 |
179 | MaterialComponents 提供了 暗色的 `Theme Overlay`
180 |
181 | 
182 |
183 | 使用该 `Theme Overlay` 可以将浅色主题中的某部分做成暗色主题
184 |
185 |
186 |
187 | ### 技巧2:使用正确的 Context
188 |
189 | 我们知道主题与 Context 相关,由于上文我们提到的主题的继承关系,使用正确的 Context 很重要
190 |
191 | 
192 |
193 | 记住:使用距离最近 View 所在的 Context
194 |
195 | 
196 |
197 |
198 |
199 | 当然更好的做法是使用主题属性
200 |
201 | 
202 |
203 |
204 |
205 | ### 技巧3:在代码中使用 Theme Overlay
206 |
207 | 如果想要在代码中使用 `Theme Overlay` ,可以将其包裹为 ContextThemeWrapper,这也是 `android:theme` 标签内部做的事情
208 |
209 | 
210 |
211 |
212 |
213 | ## 使用 Theme 和 Style
214 |
215 | ### Color
216 |
217 | 这部分内容在视频的 12.36 处
218 |
219 |
220 |
221 | 程序内最重要的资源便是 Color,Android 定义 Color 有很多种方式,比如 Color tag,它主要由 ARGB 色值组成
222 |
223 | 
224 |
225 |
226 |
227 | Color tag 也可以引用其他的 Color tag。需要注意的是,你不能在 Color tag 引用主题属性
228 |
229 | 
230 |
231 |
232 |
233 | 以上是静态的颜色,下面我们谈一谈有状态的颜色
234 |
235 | Color state list 允许你在不同状态下定义不同的颜色,它们也可以用作 drawable,例如下面的例子,在 button 按下或禁用时都有相应的颜色
236 |
237 | 
238 |
239 |
240 |
241 | 下面我们来看一下 Color state list 是如何定义的,我们看到这里使用了 `selector` 标签,本示例中有两个 item,第一项定义了一种颜色,并指定它是在选中状态下才被使用;第二项 没有定义任何状态,这意味着它是默认颜色。如果没有其他颜色可以匹配当前状态时,它就会被使用
242 |
243 |
244 |
245 | 
246 |
247 |
248 |
249 | > 这里有一个小技巧,可以将 Color state list 按照最容易出现——最不容易出现的顺序进行排序,这由其背后的实现原理决定,系统会遍历每个 item 直至找出匹配项
250 |
251 |
252 |
253 | 在 API 21 官方引入了 `android:alpha` tag 来设置透明度,并在 API 23 中可以引用主题属性。如果你使用 AppCompat 的话,它可以向下兼容到 API 14
254 |
255 | 
256 |
257 | #### 技巧1:设置透明度
258 |
259 | 我们在开发中可能会遇到这种情况:对于同一个颜色,我们需要不同的透明度。因此我们可能会复制不同透明度的色值
260 |
261 | 
262 |
263 |
264 |
265 | 你可能不想在更改一个颜色后然后再逐一更改其相应透明度的色值,此处我们可以使用 ColorStateList,我们可以使用默认颜色的功能,只配置一个 item,并在此处配置透明度(从 0 到 1)
266 |
267 | 
268 |
269 |
270 |
271 | #### 技巧2:ColorStateList 与 Drawable 的转换
272 |
273 | 我们在 View 配置 background 等属性时可以直接传入 color,在内部系统会填充该颜色并将其包装为 ColorDrawable
274 |
275 | 
276 |
277 |
278 |
279 | 但如果你将 ColorStateList 传入是不行的,在 API 28 及之前的设备会崩溃
280 |
281 | 
282 |
283 | 这是因为 ColorDrawable 是无状态的,在 Android 10 中,官方加入了 ColorStateListDrawable 解决了这一问题
284 |
285 |
286 |
287 | 为了在所有 API 中获得相同的体验,我们可以使用一种变通的做法,使用 `backgroundTint`
288 |
289 | 
290 |
291 | 此处使用纯色设置了一个矩形,接着使用 `backgroundTint` 指向了 ColorStateList
292 |
293 |
294 |
295 | ### 常用技巧
296 |
297 | 这部分内容在视频的 17.35 处
298 |
299 | #### 技巧1:正确命名资源
300 |
301 | 我们的项目中肯定有这样命名的资源,它们是按照主题属性命名的。Android Studio 新建项目默认的资源就是这样命名的
302 |
303 | 
304 |
305 |
306 |
307 | 而你的主题大概是这样,主题属性指向同名的颜色资源
308 |
309 | 
310 |
311 |
312 |
313 | 这样做是不推荐的
314 |
315 | 
316 |
317 | 我们需要的不是一个语义的命名,而是需要一个文字的命名,我们可以用品牌颜色命名,也可以像 Material Color System,根据色调命名
318 |
319 | 
320 |
321 | 
322 |
323 |
324 |
325 | #### 技巧2:使用统一的 style 名称
326 |
327 | 大家可能见过这样的样式,一个叫 AppTheme,一个叫 Toolbar,从命名便可以看出它们的用途
328 |
329 | 
330 |
331 |
332 |
333 | 但是如果我们加入了第三种样式,它的用途不是很明显,我们无法区分它是一个主题还是样式
334 |
335 | 
336 |
337 |
338 |
339 | 为此我们可以约定一个命名规则
340 |
341 | 第一部分为 Style type:主题,样式,文本外观,Theme Overlay,形状外观等等
342 |
343 | 
344 |
345 |
346 |
347 | 第二部分为 Group name:通常采用应用名称,如果是多 module 也可以为 module 名
348 |
349 | 
350 |
351 |
352 |
353 | 第三部分为 Sub-group name:这名字通常用于 Widget,也就是使用样式的 View 的名称
354 |
355 | 
356 |
357 |
358 |
359 | 第四部分为 Variant name:这是可选的,它是主题的变量
360 |
361 | 
362 |
363 |
364 |
365 | 回到最初的例子,按照我们约定的命名规范改造就变成了这样
366 |
367 | 
368 |
369 |
370 |
371 | 这里有一个值得注意的地方,在 Android System 中,`.` 是一个十分神奇的符号,这里有一个基于它的隐含的继承系统
372 |
373 | 上图的 Widget.MyApp.Toolbar.Blue 实际上继承了中间的这个主题
374 |
375 | 
376 |
377 |
378 |
379 | 这种命名规范可以在 code review 时直观地判断出 style 或 theme 是否用错。如下图,很明显这里使用了 style 标签,却传入了一个主题
380 |
381 | 
382 |
383 | 你甚至可以使用 Lint 来解决此问题,[详情移步](https://proandroiddev.com/making-android-lint-theme-aware-6285737b13bc)
384 |
385 |
386 |
387 | #### 技巧3:拆分多个文件
388 |
389 |
390 |
391 | ##### 简单模式
392 |
393 | 将资源类型文件进行标准的分类
394 |
395 | - `theme.xml` :Theme 和 Theme Overlay
396 | - `type.xml`:字体,文本外观,文本尺寸,字体文件等
397 | - `style.xml`:只有 Widget style
398 | - `dimens.xml` `colors.xml` `strings.xml`:其它类型归类于实际的资源类型
399 |
400 | 
401 |
402 |
403 |
404 | ##### 复杂模式
405 |
406 | 复杂模式是按照逻辑进行分类,例如形状相关的放入 `shape.xml`,如果想要实现全屏的UI,可以在 `sys_ui.xml` 中控制状态栏/导航栏颜色,以及是否显示等等
407 |
408 |
409 |
410 | 
411 |
412 |
413 |
414 | 在 Android Studio 的 Android 视图下,这样做的效果是很好的。如下图,可以很清晰的看到 light 主题和 dark 主题的主题文件
415 |
416 |
417 |
418 | 
419 |
420 |
421 |
422 |
423 |
424 | ## Material
425 |
426 | ### 颜色系统
427 |
428 | 这部分内容在视频的 24:00 处
429 |
430 | 该系统构建基础是大量使用语义命名的变量,这些变量都属于「主题属性」。它的运作原理是 library 展示与这些使用语义命名的颜色相关的主题属性,而开发者负责为这些颜色提供数值。在 library 内,用这些颜色构建所有的 Widget
431 |
432 |
433 |
434 | 对于颜色系统,开发者需要了解一些常用的颜色
435 |
436 | 
437 |
438 | `colorPrimary` 和 `colorSecondary` 是 app 品牌的主要颜色,Variant 为主色的对比色;`colorSurface` 十分有用,它负责在某些控件表面的颜色;`colorError` 是错误的警示色,因此你没必要在使用时硬编码这些颜色
439 |
440 |
441 |
442 | 颜色系统还会提供一些 `On` 命名的颜色,这种颜色会保证拥有和类似名称颜色形成对比的颜色,例如 `colorOnPrimary` 永远会和 `colorPrimary` 形成对比
443 |
444 | 
445 |
446 |
447 |
448 | 你可以在自己的主题中配置这些颜色,注意这里不必配置所有的颜色,如果你继承了一些 Material 主题,它们会提供所有颜色的默认色,比如下图中没有设置 `colorSurface`,则会使用 Material Light 主题内定义的 `colorSurface`
449 |
450 | 
451 |
452 |
453 |
454 | 之后你便可以在 layout 或 style 中使用这些颜色了
455 |
456 | 
457 |
458 | #### 技巧
459 |
460 | 一个有用的技巧是可以将这些颜色与 ColorStateList 结合
461 |
462 | 比如我们想做一个分割线,不必创建名为 colorDivider 的新颜色,直接从 colorOnSurface 中取一个颜色即可,这个颜色肯定会和背景色形成对比
463 |
464 | 
465 |
466 |
467 |
468 | 而且它会响应不同的主题,在浅色主题下,20% `colorOnSurface` 是一种黑中带白的颜色。在暗色主题下,`colorOnSurface` 会变成白色,此时的 20% `colorOnSurface` 会提供合适的对比
469 |
470 |
471 |
472 | 
473 |
474 |
475 |
476 | 以语义命名的颜色是十分有用的,你可以省去大量的颜色定义
477 |
478 |
479 |
480 | ### 排版系统
481 |
482 | 这部分内容在视频的 28:06 处
483 |
484 | 在设计中,通常使用固定的几种字号进行排版,例如大标题1,大标题2,文本主体,副标题,按钮等等
485 |
486 | 
487 |
488 | 而这些都是作为主题属性实现的
489 |
490 | 
491 |
492 | 然后便可以在应用中引用这些主题属性
493 |
494 | 
495 |
496 | Material 的 Text 十分强大,它可以设置行高,如果你遇到了设置行高却不生效的问题,使用 Material 组件可以解决这一问题
497 |
498 | ### 形状系统
499 |
500 | 这部分内容在视频的 30:07 处
501 |
502 | Material 采用了 [shape system](https://material.io/design/shape),该系统为小型,中型和大型组件 [提供](https://material.io/develop/android/theming/shape/) 了主题属性。请注意,如果要在自定义组件上设置 shape,则可能要使用 `MaterialShapeDrawable` 作为其背景,它可以理解并实现 shape
503 |
504 | 这里是通过 ShapeAppearance 来定义的,ShapeAppearance 和 TextAppearance 类似,是一种针对形状系统的配置
505 |
506 | 
507 |
508 | 它由几个组件组成
509 |
510 | 首先是 cornerFamily,支持圆角和切角,圆角的方向等等
511 |
512 | 
513 |
514 |
515 |
516 | ShapeAppearance 还支持 overlay,可以更改特定的 Widget
517 |
518 | 
519 |
520 |
521 |
522 | 在使用 overlay 时要注意的是很多 Material 组件是有着自己的 ShapeAppearance overlay,例如 BottomSheet,它会取消底部的圆角
523 |
524 | 
525 |
526 | #### 技巧
527 |
528 | 形状系统是由 MaterialShapeDrawable 实现的
529 |
530 | 
531 |
532 |
533 |
534 | 而 MaterialShapeDrawable 有一个强大的功能就是它有着一个属性叫 interpolation
535 |
536 | 
537 |
538 |
539 |
540 | 使用它可以为形状系统做动画,如果它的值为0,那么所配置形状不会生效,如果值为1,那么形状系统会完整地应用到 drawable 上
541 |
542 |
543 |
544 | 
545 |
546 |
547 |
548 | ## 暗黑主题
549 |
550 | 这部分内容在视频的 34:41 处
551 |
552 |
553 |
554 | 暗黑主题的适配很简单,可以通过代码设置当前主题和获取当前主题
555 |
556 | 
557 |
558 |
559 |
560 | 可以使用 Material 组件的 DayNight,这样在打开/关闭 暗黑主题时相应的主题属性的色值都会跟随变化
561 |
562 | 
563 |
564 |
565 |
566 | #### 技巧1 :抽取主题
567 |
568 |
569 |
570 | 很多时候只做上面的两步并不能很好地适配暗黑主题,例如我们的应用在浅色主题下是这样的,深色的内容在浅色的背景上
571 |
572 |
573 |
574 | 
575 |
576 |
577 |
578 | 而使用了夜间主题,可能会变成这样
579 |
580 |
581 |
582 | 
583 |
584 |
585 |
586 | 而我们想要的效果是这样的
587 |
588 |
589 |
590 | 
591 |
592 |
593 |
594 | 这是由于设置颜色时硬编码导致的
595 |
596 | 
597 |
598 |
599 |
600 | 实际上,这种情况使用主题属性会有更好的效果
601 |
602 | 
603 |
604 |
605 |
606 | 如果想要 `colorPrimary` 在不同的主题下使用不同的颜色,我们应该如何设置?
607 |
608 | 
609 |
610 |
611 |
612 | 或许你会在 `values-night/colors.xml` 为暗色主题定义色值,**但不建议这样做!**
613 |
614 | 
615 |
616 |
617 |
618 | **最好的做法是抽取公共部分到基础主题,然后在此基础上对浅色和深色主题分别配置差异化的属性**
619 |
620 | 
621 |
622 |
623 |
624 | #### 技巧2:ColorPrimary 的使用
625 |
626 | 有些时候我们的 colorPrimary 是一种亮色,例如下图中的蓝色,但在暗黑主题下我们想使用相对较暗的颜色,例如 `?attr/colorSurface`,Material 组件内部为我们做好了转换,直接使用 `?attr/colorPrimarySurface` 即可
627 |
628 | 
629 |
630 |
631 |
632 | ## Demo
633 |
634 | [demo地址在这里](https://github.com/Flywith24/Flywith24-Theme-demo),如果感觉对你有帮助的话,点一颗小星星吧~ 😉
635 |
636 |
637 |
638 |
639 | ## 关于我
640 |
641 | 我是 [Flywith24](https://flywith24.gitee.io/),我的博客内容已经分类整理 [在这里](https://github.com/Flywith24/BlogList),点击右上角的 Watch 可以及时获取我的文章更新哦 😉
642 |
643 | - [掘金](https://juejin.im/user/57c7f6870a2b58006b1cfd6c)
644 |
645 | - [简书](https://www.jianshu.com/u/3d5ad6043d66)
646 |
647 | - [Github](https://github.com/Flywith24)
648 |
649 |
650 |
651 | 
652 |
--------------------------------------------------------------------------------