I created this app with Kotlin.
We have two mode Blak and Light!
Figma Link: https://www.figma.com/file/wrrHncYtoPX9mW72TASyC1/Blog-App-UI-KIT-(Community)-(Community)?node-id=4%3A351
APK file:
I use SharedPreferences:
class MySharedPreference(context: Context) {
private val appSharedPrefs = context.getSharedPreferences("have", Context.MODE_PRIVATE)
fun setPreferences(key: String?, value: String?) {
val prefsEditor = appSharedPrefs?.edit()
prefsEditor?.putString(key, value)
prefsEditor?.apply()
}
fun getPreferences(key: String?): String? {
val json = appSharedPrefs?.getString(key, "")
return if (TextUtils.isEmpty(json)) {
null
} else json
}
}
And ThemeHelper Object for lightmode and darkmode:
object ThemeHelper {
const val lightMode = "light"
const val darkMode = "dark"
const val batterySaverMode = "battery"
const val default = "default"
fun applyTheme(theme: String) {
when (theme) {
lightMode -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
darkMode -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
batterySaverMode -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY)
default -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
}
}
}
In Main Activity we use these classes:
mySharedPreference = MySharedPreference(this)
if (mySharedPreference.getPreferences("isDark") == "1") {
ThemeHelper.applyTheme(ThemeHelper.darkMode)
binding.switch1.isChecked = true
} else {
ThemeHelper.applyTheme(ThemeHelper.lightMode)
binding.switch1.isChecked = false
}
So, when user select DarkMode SharedPreferences value is "1" else common LightMode
Comments