在语言更改时保留 ListPreference 值

Preserving ListPreference value on language change

如何在语言更改时保留 ListPreference 的值,知道它在首选项中记录翻译后的字符串值?

  1. 打开英文应用,select一个值。这是 data/data 中 preferences.xml 中保存的内容:<string name="list_preference">Home</string>

  2. 更改语言。例如,在法语中字符串是“Travail”,但没有执行自动对应。摘要变为“未设置”,我们无法再访问此首选项的预期值。

看来要么我们遗漏了什么,要么存在重大设计缺陷。

目前只是示例代码,但如果您需要详细信息:

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>

访问值

// 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), ""))

我们就是这样解决的。我们更改了 entryValues 以引用非本地化字符串数组。

<ListPreference
    android:defaultValue=""
    android:entries="@android:array/emailAddressTypes"
    android:entryValues="@array/listExample_values_array"
    android:key="@string/pref_listExample_string"
    android:title="List preference" />

值定义如下:

<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>

可以在代码中使用 getString(R.strings...) 访问这些值,以与实际偏好值进行比较。