首页 > 解决方案 > 如何使 switchButton 在 jetPack 数据存储中进行更改并采用数据各自值的位置?

问题描述

我想做的是:

  1. 将 switchButton "switchTranslationDirection" 设置为打开片段时的相应位置;
  2. 为了使它在每次打开 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")
    }
}

标签: androidkotlinandroid-jetpackandroid-viewmodeloncheckedchanged

解决方案


推荐阅读