I would like to add a button to my app on the home screen, so that when you click on this button, the dark mode appears. Dark mode has already been set up and everything is running. However, only if the user of this app is also in dark mode with his mobile phone. But I would like everyone to have the opportunity to switch to dark mode in the app themselves. I hope you can understand my question what I mean, my English is not that good so sorry
Asked
Active
Viewed 103 times
3 Answers
2
Use API AppCompatDelegate.setDefaultNightMode()
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
You'll find this article from Google's Chris Banes useful:
https://medium.com/androiddevelopers/appcompat-v23-2-daynight-d10f90c83e94
You should consider adding an app preference via a Settings button as described in the above article

CSmith
- 13,318
- 3
- 39
- 42
-
1this is the only correct answer here – a_local_nobody Nov 05 '20 at 20:19
1
How I understand you already have DarkMode style and Default style. You can add a Switch for that on your MainActivity, and save your darkMode state in SharedPreferences class. Make a condition:
if (Switch is enabled) {
setTheme(R.style.darkMode)
}else {
setTheme(R.style.defaultMode)
}
For more details, you can watch some tutorials on youtube on how to do that. https://www.youtube.com/watch?v=xqY7Yu5C8pg

Andrei Meriacre
- 114
- 1
- 7
1
As you already defined DarkMode may be in drawable. So you can switch background by the following code.
if (true) {
button.setBackgroundResource(R.drawable.darkmode);
}else {
button.setBackgroundResource(R.drawable.defaultmode);
}

Ayaz khan
- 153
- 5
- 16