Создаем портфолио за 1 месяц
К концу месяца: 4 классных проекта в вашем портфолио! Стоимость: 100$. Подробности...
439 of 502 menu
◀ ▶

Функция intPreferencesKey

Функция intPreferencesKey возвращает Preferences.Key для int. Имя передают в name, значение пишут в edit и читают из Preferences.

Синтаксис

val key = intPreferencesKey("abcde")

Параметры

Параметр Описание
name Строковое имя пары в файле prefs.

Пример

Давайте сохраним int по ключу 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.intPreferencesKey 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 = intPreferencesKey("abcde") lifecycleScope.launch { val snapshot = dataStore.edit { it[key] = 12345 } val res = snapshot[key]?.toString() ?: "abcde" setContent { Text(text = res) } } } }

В prefs сохранится 12345, на экране Text покажет "12345".

Пример

Давайте обновим int в том же edit:

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.intPreferencesKey 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 = intPreferencesKey("12345") lifecycleScope.launch { dataStore.edit { it[key] = 12345 } val snapshot = dataStore.edit { it[key] = 12345 } val res = snapshot[key]?.toString() ?: "abcde" setContent { Text(text = res) } } } }

По ключу "12345" останется значение 12345.

Смотрите также

  • функция longPreferencesKey,
    которой задают ключ long
  • метод putInt,
    аналог записи int в SharedPreferences
  • функция stringPreferencesKey,
    которой задают строковый ключ
  • метод edit,
    куда передают prefs[key] = value
← →
↑
Мы используем cookie для работы сайта, аналитики и персонализации. Обработка данных происходит согласно Политике конфиденциальности.
принять все настроить отклонить