Функция stringPreferencesKey
Функция stringPreferencesKey возвращает
Preferences.Key для строки.
Имя ключа передают в name,
затем ключ используют в
edit
и при чтении
Preferences.
Синтаксис
val key = stringPreferencesKey("abcde")
Параметры
| Параметр | Описание |
|---|---|
name |
Строковое имя пары в файле prefs. |
Пример
Давайте запишем строку по ключу abcde:
import android.content.Context
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.Text
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
private val Context.dataStore by preferencesDataStore(name = "prefs")
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val key = stringPreferencesKey("abcde")
lifecycleScope.launch {
val snapshot = dataStore.edit { it[key] = "12345" }
val res = snapshot[key] ?: "abcde"
setContent {
Text(text = res)
}
}
}
}
В prefs сохранится "12345"
по ключу "abcde".
Пример
Давайте создадим два строковых ключа:
import android.content.Context
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.Text
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
private val Context.dataStore by preferencesDataStore(name = "prefs")
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val keyA = stringPreferencesKey("abcde")
val keyB = stringPreferencesKey("12345")
lifecycleScope.launch {
val snapshot = dataStore.edit { prefs ->
prefs[keyA] = "12345"
prefs[keyB] = "abcde"
}
val res = snapshot[keyB] ?: "abcde"
setContent {
Text(text = res)
}
}
}
}
По ключу "12345" прочитается "abcde",
на экране Text покажет эту строку.
Смотрите также
-
функция
intPreferencesKey,
которой задают ключ для int -
класс
Preferences,
где читают prefs[key] -
метод
getString,
аналог чтения строки в xml -
функция
preferencesDataStore,
которой открывают файл prefs