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 的代码
#008577 #00574B #D81B60 #000000 #ffffff #008adb #FF039BE5 #FF01579B #FF40C4FF #FF00B0FF #66000000 #ffffff
values-night/colors.xml 的代码
#111111 #00574B #D81B60 #000000 #ffffff #008adb #FF039BE5 #FF01579B #FF40C4FF #FF00B0FF #66000000 #111111
在xml添加上背景色即可:
在你想要activity开启深色主题适配即可
效果图如下:
代码仅供参考~



