Android深色模式适配-深色主题工具类
package com.example.kotlindemo.utils
import android.content.Context
import android.content.res.Configuration
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.edit
object DarkThemeUtil {
private const val DATA_NAME = "DayNight"
fun isDarkTheme(context: Context): Boolean {
val flag = context.resources.configuration.uiMode and
Configuration.UI_MODE_NIGHT_MASK
return flag == Configuration.UI_MODE_NIGHT_YES
}
fun DefaultTheme() {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
}
fun openDarkTheme() {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
}
fun closeDarkTheme() {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
fun writeDarkThemeState(context: Context, state: Boolean) {
context.getSharedPreferences(DATA_NAME, Context.MODE_PRIVATE)
.edit{ putBoolean("boolean_dark_theme_state", state) }
}
fun readDarkThemeState(context: Context): Boolean {
return context.getSharedPreferences(DATA_NAME, Context.MODE_PRIVATE)
.getBoolean("boolean_dark_theme_state", false)
}
}
下面我用color中的background_color公用背景色来展示,说白了就是不同模式下Android会自动切换你设置好的颜色。
values/colors.xml 的代码
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
<color name="color_000000">#000000</color>
<color name="color_ffffff">#ffffff</color>
<color name="color_008adb">#008adb</color>
<color name="light_blue_600">#FF039BE5</color>
<color name="light_blue_900">#FF01579B</color>
<color name="light_blue_A200">#FF40C4FF</color>
<color name="light_blue_A400">#FF00B0FF</color>
<color name="black_overlay">#66000000</color>
<color name="background_color">#ffffff</color>
</resources>
values-night/colors.xml 的代码
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#111111</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
<color name="color_000000">#000000</color>
<color name="color_ffffff">#ffffff</color>
<color name="color_008adb">#008adb</color>
<color name="light_blue_600">#FF039BE5</color>
<color name="light_blue_900">#FF01579B</color>
<color name="light_blue_A200">#FF40C4FF</color>
<color name="light_blue_A400">#FF00B0FF</color>
<color name="black_overlay">#66000000</color>
<color name="background_color">#111111</color>
</resources>
在xml添加上背景色即可:
在你想要activity开启深色主题适配即可
效果图如下:
代码仅供参考~
|