Add SharedPrefs helper class to access shared preferences
This commit is contained in:
BinTianqi
2025-02-07 15:51:01 +08:00
parent 5e18c2684c
commit 5e109d74b1
17 changed files with 140 additions and 125 deletions

View File

@@ -1,8 +1,6 @@
package com.bintianqi.owndroid
import android.app.Application
import android.content.Context
import android.os.Build
import android.os.Bundle
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
@@ -16,19 +14,13 @@ class MyViewModel(application: Application): AndroidViewModel(application) {
val userRestrictions = MutableStateFlow(Bundle())
init {
val sharedPrefs = application.getSharedPreferences("data", Context.MODE_PRIVATE)
theme.value = ThemeSettings(
materialYou = sharedPrefs.getBoolean("material_you", Build.VERSION.SDK_INT >= 31),
darkTheme = if(sharedPrefs.contains("dark_theme")) sharedPrefs.getBoolean("dark_theme", false) else null,
blackTheme = sharedPrefs.getBoolean("black_theme", false)
)
val sp = SharedPrefs(application)
theme.value = ThemeSettings(sp.materialYou, sp.darkTheme, sp.blackTheme)
viewModelScope.launch {
theme.collect {
val editor = sharedPrefs.edit()
editor.putBoolean("material_you", it.materialYou)
if(it.darkTheme == null) editor.remove("dark_theme") else editor.putBoolean("dark_theme", it.darkTheme)
editor.putBoolean("black_theme", it.blackTheme)
editor.commit()
sp.materialYou = it.materialYou
sp.darkTheme = it.darkTheme
sp.blackTheme = it.blackTheme
}
}
}
@@ -36,6 +28,6 @@ class MyViewModel(application: Application): AndroidViewModel(application) {
data class ThemeSettings(
val materialYou: Boolean = false,
val darkTheme: Boolean? = null,
val darkTheme: Int = -1,
val blackTheme: Boolean = false
)