How can the value of a ListPreference be preserved on language change, knowing that it records in the preference the translated string value?
Open the application in English, select a value. Here is what is saved in the preferences.xml in data/data: <string name="list_preference">Home</string>
Change the language. For example, in French the string is "Travail", but nothing performs an automatic correspondance. The summary becomes "Not Set" and we can't access the intended value of this preference anymore.
It seems like either we are missing something, either there is a major design flaw.
It is just sample code for now, but if you want the details:
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preferences, rootKey)
val listPreference: ListPreference? = findPreference(getString(R.string.pref_listExample_string))
listPreference?.summaryProvider = ListPreference.SimpleSummaryProvider.getInstance()
}
}
preferences.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
android:defaultValue=""
android:entries="@android:array/emailAddressTypes"
android:entryValues="@android:array/emailAddressTypes"
android:key="@string/pref_listExample_string"
android:title="List preference (to be localized)" />
</PreferenceScreen>
preference_ids.xml
<resources>
<string name="pref_listExample_string">listExample</string>
</resources>
To access the value
// This is a problem : how can we access an unlocalized value of the string representation?
val sharedPrefs : SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
Log.i(TAG, sharedPrefs.getString(getString(R.string.pref_listExample_string), ""))
This is how we solved it. We changed entryValues to refer to an array of non-localized strings.
<ListPreference
android:defaultValue=""
android:entries="@android:array/emailAddressTypes"
android:entryValues="@array/listExample_values_array"
android:key="@string/pref_listExample_string"
android:title="List preference" />
The values are defined as follows :
<string-array name="listExample_values_array">
<item>@string/listExample_home</item>
<item>@string/listExample_work</item>
<item>@string/listExample_other</item>
<item>@string/listExample_custom</item>
</string-array>
<string name="listExample_home">home</string>
<string name="listExample_work">work</string>
<string name="listExample_other">other</string>
<string name="listExample_custom">custom</string>
These values can be accessed with getString(R.strings...) in code to compare with the actual preference value.