所以,基本上我有一个班级:
class App : Application() {
lateinit var prefs: SharedPreferences
}
现在,我想添加一个委托属性:
var isInitialized: Boolean by prefs.boolean()
问题在于, isInitialized 属性必须懒得初始化,因为我使用Android Dagger2框架,该框架在 App 创建后执行注入(在调用<期间) strong> onCreate()方法):
class App : Application() {
lateinit var prefs: SharedPreferences
var isInitialized: Boolean = false
override fun onCreate() {
super.onCreate()
// how can I assign a delegate to isInitialized?
}
}
我希望通过以下方式完成:
有没有办法做到这一点?
谢谢!
答案 0 :(得分:1)
你可以使用间接方式来执行此操作:
class DoubleDelegate<R, T>(var realDelegate: ReadWriteProperty<R, T> = /* some default */) : ReadWriteProperty<R, T> by realDelegate
然后
val isInitializedDelegate = DoubleDelegate<App, Boolean>()
var isInitialized: Boolean by isInitializedDelegate
override fun onCreate() {
super.onCreate()
isInitializedDelegate.realDelegate = prefs.boolean()
}
不知怎的,我不认为这实际上是个好主意。
答案 1 :(得分:0)
使用懒惰
从文档Lazy获取当前Lazy实例的延迟初始化值。一旦初始化了值,它就不能在这个Lazy实例的剩余生命周期内改变。
申请类
val prefs: Prefs by lazy {
App.prefs!!
}
class App : Application() {
companion object {
var prefs: Prefs? = null
}
override fun onCreate() {
prefs = Prefs(applicationContext)
super.onCreate()
}
}
您的数据模型类应该是这样的
class Prefs (context: Context) {
val PREFS_FILENAME = "com.teamtreehouse.colorsarefun.prefs"
val IsInitialized = "isInitialized"
val prefs: SharedPreferences = context.getSharedPreferences(PREFS_FILENAME, 0);
var initialized: Boolean
get() = prefs. getBoolean(IsInitialized, false)
set(value) = prefs.edit(). putBoolean(IsInitialized, value).apply()
}
然后使用Activity或片段
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val initialized = prefs.initialized //getvalue
selectvalue(false)// set value
}
private fun selectvalue(value: Boolean) {
prefs.initialized = value
}
}
更多细节请参阅此示例SharedPreferences Easy with Kotlin