SettingsFragment.kt 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package im.angry.openeuicc.ui
  2. import android.content.Intent
  3. import android.net.Uri
  4. import android.os.Bundle
  5. import androidx.datastore.preferences.core.Preferences
  6. import androidx.lifecycle.lifecycleScope
  7. import androidx.preference.CheckBoxPreference
  8. import androidx.preference.Preference
  9. import androidx.preference.PreferenceFragmentCompat
  10. import im.angry.openeuicc.common.R
  11. import im.angry.openeuicc.util.*
  12. import kotlinx.coroutines.flow.Flow
  13. import kotlinx.coroutines.launch
  14. import kotlinx.coroutines.runBlocking
  15. class SettingsFragment: PreferenceFragmentCompat() {
  16. override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
  17. setPreferencesFromResource(R.xml.pref_settings, rootKey)
  18. findPreference<Preference>("pref_info_app_version")
  19. ?.summary = requireContext().selfAppVersion
  20. findPreference<Preference>("pref_info_source_code")
  21. ?.setOnPreferenceClickListener {
  22. startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(it.summary.toString())))
  23. true
  24. }
  25. findPreference<CheckBoxPreference>("pref_notifications_download")
  26. ?.bindBooleanFlow(preferenceRepository.notificationDownloadFlow, PreferenceKeys.NOTIFICATION_DOWNLOAD)
  27. findPreference<CheckBoxPreference>("pref_notifications_delete")
  28. ?.bindBooleanFlow(preferenceRepository.notificationDeleteFlow, PreferenceKeys.NOTIFICATION_DELETE)
  29. findPreference<CheckBoxPreference>("pref_notifications_enable")
  30. ?.bindBooleanFlow(preferenceRepository.notificationEnableFlow, PreferenceKeys.NOTIFICATION_ENABLE)
  31. findPreference<CheckBoxPreference>("pref_notifications_disable")
  32. ?.bindBooleanFlow(preferenceRepository.notificationDisableFlow, PreferenceKeys.NOTIFICATION_DISABLE)
  33. }
  34. private fun CheckBoxPreference.bindBooleanFlow(flow: Flow<Boolean>, key: Preferences.Key<Boolean>) {
  35. lifecycleScope.launch {
  36. flow.collect { isChecked = it }
  37. }
  38. setOnPreferenceChangeListener { _, newValue ->
  39. runBlocking {
  40. preferenceRepository.updatePreference(key, newValue as Boolean)
  41. }
  42. true
  43. }
  44. }
  45. }