Closed dusauton closed 2 years ago
It does work with PreferenceFragmentCompat(), but I'm doing it slightly differently than you. Try it out.
class SettingsFragment : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener {
private lateinit var sharedPref: SharedPreferences
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.root_preferences, rootKey)
sharedPref = requireActivity().getSharedPreferences(MAIN_PREFERENCES, Context.MODE_PRIVATE)
}
override fun onResume() {
super.onResume()
preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
override fun onPause() {
super.onPause()
preferenceScreen.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
when (key) {
"theme" -> {
.
.
.
}
"language" -> {
val languageCode = sharedPreferences?.getString("language", "nl") ?: "nl"
val editor: SharedPreferences.Editor = sharedPref.edit()
editor.putString(LANGUAGE_KEY, languageCode)
editor.apply()
updateLanguage(languageCode)
updatePreference(key)
}
else -> {
.
.
.
}
}
}
private fun updatePreference(key: String) {
val pref: Preference? = findPreference(key)
if (pref is ListPreference) {
val listPref: ListPreference = pref
pref.value?.let {
pref.setSummary(listPref.entry)
if (key.equals("language", true)) {
.
.
.
}
}
}
}
private fun updateLanguage(languageCode: String) {
(activity as? LocalizationActivity)?.setLanguage(languageCode)
.
.
.
}
}
Great, I have implemented it in a similar way now, thanks for the detailed answer!
This is more of a improvement request. I am trying to use the setLanguage in a PreferenceFragmentCompat class, using setOnPreferenceChangeListener. However, I cannot get the context from this class, and the setLanguage function does not seem to work... any workaround to implement it within this PreferenceFragmentCompat?
Thanks!
package ferm.myapp.fermentablebread.ui.settings
import android.os.Bundle import androidx.preference.ListPreference import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import com.akexorcist.localizationactivity.core.LanguageSetting.setLanguage import ferm.myapp.fermentablebread.R import java.util.*
class SettingsFragment : PreferenceFragmentCompat() {
}