在自定义的 Property delegate 中添加 'getValue(Context, KProperty<*>)' 方法即可。例如,以下是一个名为 StringPreference 的 Property delegate 的示例代码:
import android.content.Context
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
private val Context.dataStore by preferencesDataStore("data_store")
class StringPreference(private val key: String) {
operator fun getValue(context: Context, property: KProperty<*>): String {
val preferencesKey = stringPreferencesKey(key)
val dataStore = context.dataStore
val valueFlow = dataStore.data.map { preferences ->
preferences[preferencesKey] ?: ""
}
return runBlocking { valueFlow.first() }
}
operator fun setValue(context: Context, property: KProperty<*>, value: String) {
val preferencesKey = stringPreferencesKey(key)
val dataStore = context.dataStore
runBlocking {
dataStore.edit { preferences ->
preferences[preferencesKey] = value
}
}
}
}
使用示例:
class MainActivity : AppCompatActivity() {
private val stringPreference by lazy { StringPreference("key_name") }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val value = stringPreference.getValue(this, ::stringPreference)
Log.d("StringPreferenceTest", "Value: $value")
stringPreference.setValue(this, ::stringPreference, "NewValue")
}
}