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

Функция floatPreferencesKey

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

Синтаксис

val key = floatPreferencesKey("abcde")

Параметры

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

Пример

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

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

Пример

Давайте обновим float вторым 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.floatPreferencesKey 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 = floatPreferencesKey("12345") lifecycleScope.launch { dataStore.edit { it[key] = 12345f } val snapshot = dataStore.edit { it[key] = 12345f } val res = snapshot[key]?.toInt()?.toString() ?: "abcde" setContent { Text(text = res) } } } }

По ключу "12345" останется float, на экране снова будет "12345".

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

  • функция intPreferencesKey,
    которой задают целочисленный ключ
  • функция longPreferencesKey,
    которой задают long-ключ
  • класс DataStore,
    куда пишут через edit
  • класс Preferences,
    снимок, из которого читают float
← →
↑
Мы используем cookie для работы сайта, аналитики и персонализации. Обработка данных происходит согласно Политике конфиденциальности.
принять все настроить отклонить