/ 安卓笔记  

Android 10 "Dark Mode"适配指南

Android 10于近期推出,Google在前段时间的开发者大会上正式发布了本系统,Android 10带来了一系列的新特性,其中有一项更新是支持了系统级的Dark Mode(深色模式)。Dark Mode的适配特别简单,下面我们来看下😂

检测是否开启Dark Mode

1
2
3
4
fun getDarkModeStatus(context: Context): Boolean {
val mode = context.resources.configuration.uiMode and UI_MODE_NIGHT_MASK
return mode == UI_MODE_NIGHT_YES
}

设置不同的主题

先定义两套主题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<resources>

<style name="AppThemeLight" parent="Theme.AppCompat.DayNight.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="colorMainBg">@color/colorBg</item>
<item name="colorMainText">@color/colorText</item>
</style>

<style name="AppThemeDark" parent="Theme.AppCompat.DayNight.DarkActionBar">
<item name="colorPrimary">@color/colorPrimaryByDark</item>
<item name="colorPrimaryDark">@color/colorPrimaryDarkByDark</item>
<item name="colorAccent">@color/colorAccentByDark</item>
<item name="colorMainBg">@color/colorBgByDark</item>
<item name="colorMainText">@color/colorTextByDark</item>
</style>

</resources>

自定义属性如下

1
2
3
4
5
6
7
8
<resources>

<!--主体背景色-->
<attr name="colorMainBg" format="color"/>
<!--主体文字颜色-->
<attr name="colorMainText" format="color"/>

</resources>

颜色值如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<resources>
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>

<color name="colorPrimaryByDark">#2B2B2B</color>
<color name="colorPrimaryDarkByDark">#161616</color>
<color name="colorAccentByDark">#2A3785</color>

<color name="colorBg">#FFFFFF</color>
<color name="colorBgByDark">#252525</color>

<color name="colorText">#000000</color>
<color name="colorTextByDark">#CCCCCC</color>

</resources>

动态切换

BaseActivity中,根据getDarkModeStatus方法返回的值判断是否开启深色模式,来分别设置不同的theme就OK啦

1
2
3
4
5
6
7
8
9
10
private fun checkDarkMode() {

//true: 开启Dark Mode , false: 关闭Dark Dode
if (DisplayUtils.getDarkModeStatus(this)) {
setTheme(R.style.AppThemeDark)
} else {
setTheme(R.style.AppThemeLight)
}

}

切换效果

Light Mode Dark Mode

总结

适配深色模式不难,关键在于提取项目中的颜色属性,分门别类,这样就比较清晰