首页 > 解决方案 > 无法切换到任何主题,如深色、浅色、系统等

问题描述

即使更改选项也可以正常工作,我也无法切换主题,sharedpreferences 为最后选择的主题保留了正确的值。

我的应用程序.kt

class MyApp : Application() {

    override fun onCreate() {
       super.onCreate()
       AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.getDefaultNightMode())
    }
}

主题.xml

 <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowTranslucentNavigation">true</item>
        <item name="android:navigationBarColor">@android:color/transparent</item>
 </style>

MainActivity.kt

binding.themeGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.themeLight -> setTheme(AppCompatDelegate.MODE_NIGHT_NO, THEME_LIGHT)
                R.id.themeDark -> setTheme(AppCompatDelegate.MODE_NIGHT_YES, THEME_DARK)
                R.id.themeBattery -> setTheme(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY, THEME_BATTERY)
                R.id.themeSystem -> setTheme(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM, THEME_SYSTEM)
            }
        }

private fun setTheme(themeMode: Int, prefsMode: Int) {
        AppCompatDelegate.setDefaultNightMode(themeMode)
        storeTheme(prefsMode)
        //activity?.recreate() // no luck w/o commenting
    }

我有 2 个文件夹,valuesvalues-night. 每个都有各自的颜色。theme.xml里面只有 1 个values文件夹。

标签: androidandroid-themeandroid-stylesandroid-dark-themekotlin-android

解决方案


推荐阅读