I have this app, and I’d like to update the theme dynamically depending on what the user selects. Currently the setTheme() only works when the app loads for the first time. Do you have a strategy or tips you can share on how to set custom theme dynamically? Or alteast how to update the colorPrimaryVariant color dynamically.
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.Theme_CleanNoteApp_Category) // working fine when the app loads
super.onCreate(savedInstanceState)
}
CodePudding user response:
You can use this approach(line of code) to change the theme during runtime programmatically:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
You can use something like:
binding.btnChangeTheme.setOnClickListener{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
CodePudding user response:
I found a trick. We can store a reference using SharePref whenever a user selects a theme they want. Then call recreate() method to restart the Activity lifecycle. On the onCreate just read the reference from the SharedPref set by user and call setTheme(R.style.user_dynamic_theme).