Android 日间夜间模式

it2024-10-27  37

设置应用日间、夜间模式显示

1、修改 style 样式中的应用主题、其他需要配置的主题,基于这个 base 添加

<!-- Base application theme. --> <style name="BaseAppTheme" parent="@style/Theme.AppCompat.DayNight"> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <!--关闭启动窗口--> <item name="android:windowDisablePreview">true</item> <item name="android:listDivider">@drawable/bg_divider</item> </style>

2、新增 values-night 资源文件夹

在 colors.xml 中配置色值,需要注意点的是跟 values 文件夹下的 colors.xml 的key值一样

3、配合 SharedPreference 共同使用

//在 Application 初始化的时候调用 private fun initTheme() { if (SettingUtils.getIsNightMode()) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) } }

4、点击按钮修改当前显示模式

// View 的点击事件 private fun initListener() { btn.setOnClickListener { if (SettingUtils.getIsNightMode()) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) // 记录当前显示模式到 sp 配置文件中 SettingUtils.setIsNightMode(false) } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) // 记录当前显示模式到 sp 配置文件中 SettingUtils.setIsNightMode(true) } } }
最新回复(0)