1.如何适配深夜模式?
1)分别在values和values-night文件下的themes.xml自定义一个主题。这个主题继承自系统的 Theme.MaterialComponents.Light。同样,Theme中用到的颜色,也得values和values-night中分别定义。系统会根据不同的模式,加载不同文件下的Theme和Color。
<style name="Theme.MyApp" parent="Theme.MaterialComponents.Light">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
<!--禁用app的深夜模式,同时代码中也做相应的修改-->
<item name="android:forceDarkAllowed" tools:targetApi="q"> false</item>
</style>
2)AndroidManifest.xml中使用上面的主题。
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:name=".MyApp"
android:theme="@style/Theme.MyApp">
2.代码中进行模式的设置。
四种模式:
AppCompatDelegate.MODE_NIGHT_YES:设置夜间模式
AppCompatDelegate.MODE_NIGHT_NO:设置日间模式
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM:跟随系统设置决定是否设置夜间模式
AppCompatDelegate.MODE_NIGHT_AUTO:根据当前时间自动切换模式
//开启深夜模式
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
//开启普通模式
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
3.在AndroidQ版本后,如果应用没有适配深夜模式,那么系统会自动为应用自动适配深夜模式。
如果想要关闭这个功能,不跟随系统进行模式的选择。
需要在 <style name="Theme.MyApp" parent="Theme.MaterialComponents.Light"> 主题下,增加一个配置:
<item name="android:forceDarkAllowed" tools:targetApi="q"> false</item>
这句话的意思,强制允许深夜模式,如果设置为false,在系统设置为黑夜模式后,就不会强制应用改变为深夜模式。
接下来看一个demo。
Demo下载链接:android暗夜模式demo-Android文档类资源-CSDN下载