android - 如何使 switchButton 在 jetPack 数据存储中进行更改并采用数据各自值的位置?
问题描述
我想做的是:
- 将 switchButton "switchTranslationDirection" 设置为打开片段时的相应位置;
- 为了使它在每次打开 Fragment 时在 dataStore Noew 中进行相应的更改,switchButton 总是关闭
在片段中:
@AndroidEntryPoint
class SettingsFragment : Fragment(R.layout.settings_layout) {
private val viewModel: SettingsViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = SettingsLayoutBinding.bind(view)
binding.apply {
viewModel.readTransDir.observe(viewLifecycleOwner) {
if (it) {
switchTranslationDirection.isChecked
switchTranslationDirection.text = "Native to swedish"
} else {
!switchTranslationDirection.isChecked
switchTranslationDirection.text = "Swedish to native"
}
switchTranslationDirection.setOnCheckedChangeListener { compoundButton, b -> viewModel.saveTransDir(compoundButton.isChecked) }
}
}
}
}
在视图模型中:
class SettingsViewModel @ViewModelInject constructor(
private val preferencesManager: PreferencesManager
) : ViewModel() {
private val translationDirectionFlow = preferencesManager.translationDirectionFlow
val readTransDir = translationDirectionFlow.asLiveData()
fun saveTransDir(nativToForeign: Boolean) = viewModelScope.launch {
preferencesManager.updateTranslationDirection(nativToForeign)
}
}
在 JetPack 数据存储首选项管理器中:
@Singleton
class PreferencesManager @Inject constructor(@ApplicationContext context: Context) {
private val dataStore = context.createDataStore("user_preferences")
val translationDirectionFlow = dataStore.data
.catch { exception ->
if (exception is IOException) {
Log.e(TAG, "Error reading preferences", exception)
emit(emptyPreferences())
} else {
throw exception
}
}
.map { preferences ->
val nativToForeign = preferences[PreferencesKeys.NATIV_TO_FOREIGN] ?: false
nativToForeign
}
suspend fun updateTranslationDirection(nativToForeign: Boolean) {
dataStore.edit { preferences ->
preferences[PreferencesKeys.NATIV_TO_FOREIGN]
}
}
private object PreferencesKeys {
val NATIV_TO_FOREIGN = preferencesKey<Boolean>("nativ_to_foreign")
}
}
解决方案
推荐阅读
- data-structures - AVL树:叶子深度之间的差异?
- ms-access - 访问 - 存储在文本框中的 GUID 值,不能在 SELECT 语句中使用
- python - Python with statement: '语法错误:无效语法'
- java - Libgdx Box2d 身体在坠落时失去速度
- android - 通过更改菜单中的请求 URL 对 JSON 数组进行排序
- c# - .NET webapi 响应慢 | IIS 花费的时间超过了应用程序执行所花费的平均时间
- amazon-web-services - 如何使我的集装箱港口可以在集装箱外进入?ECS-AWS
- makefile - 并非所有变量都在 Makefile 中递归扩展
- npm - 使用 NPM 安装引导程序
- javascript - JSON 表示转换