...
 
Commits (4)
package net.dankito.utils.android.ui.activities
import android.content.SharedPreferences
import android.os.Bundle
import android.preference.PreferenceManager
import android.support.v7.app.AppCompatActivity
import net.dankito.utils.android.ui.theme.Theme
abstract class ThemeableActivity : AppCompatActivity() {
protected abstract fun getSelectedTheme(): Theme
companion object {
const val SelectedThemePreferenceKeySuffix = "selected_theme"
}
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(getSelectedTheme().styleResourceId)
getSelectedTheme()?.let { theme ->
setTheme(theme.styleResourceId)
}
super.onCreate(savedInstanceState)
}
protected open fun getSelectedTheme(): Theme? {
getNullableStringPreferenceValue(getThemeNamePreferenceKey())?.let { themeName ->
return getThemeForName(themeName)
}
return null
}
protected open fun getThemeForName(themeName: String): Theme? {
return null
}
protected open fun setTheme(theme: Theme) {
setTheme(theme.styleResourceId)
writeStringPreferenceValue(getThemeNamePreferenceKey(), theme.name)
themeChanged()
}
protected open fun themeChanged() {
recreate()
}
protected open fun getSharedPreferences(): SharedPreferences {
return PreferenceManager.getDefaultSharedPreferences(this)
}
@JvmOverloads
protected open fun getNullableStringPreferenceValue(preferenceKey: String, defaultValue: String? = null): String? {
return getSharedPreferences().getString(preferenceKey, defaultValue)
}
protected open fun getStringPreferenceValue(preferenceKey: String, defaultValue: String): String {
return getSharedPreferences().getString(preferenceKey, defaultValue)
}
@JvmOverloads
protected open fun getBooleanPreferenceValue(preferenceKey: String, defaultValue: Boolean = false): Boolean {
return getSharedPreferences().getBoolean(preferenceKey, defaultValue)
}
@JvmOverloads
protected open fun getIntPreferenceValue(preferenceKey: String, defaultValue: Int = 0): Int {
return getSharedPreferences().getInt(preferenceKey, defaultValue)
}
protected open fun writeStringPreferenceValue(preferenceKey: String, value: String) {
getSharedPreferences().edit().putString(preferenceKey, value).apply()
}
protected open fun writeBooleanPreferenceValue(preferenceKey: String, value: Boolean) {
getSharedPreferences().edit().putBoolean(preferenceKey, value).apply()
}
protected open fun writeIntPreferenceValue(preferenceKey: String, value: Int) {
getSharedPreferences().edit().putInt(preferenceKey, value).apply()
}
protected open fun getThemeNamePreferenceKey(): String {
return getPreferenceKeyWithPackageNamePrefix(SelectedThemePreferenceKeySuffix)
}
protected open fun getPreferenceKeyWithPackageNamePrefix(preferenceKeySuffix: String): String {
return this.packageName + "." + preferenceKeySuffix
}
}
\ No newline at end of file
......@@ -13,4 +13,10 @@ class Theme @JvmOverloads constructor(
*/
val styleResourceId: Int
)
\ No newline at end of file
) {
override fun toString(): String {
return name
}
}
\ No newline at end of file