繁体   English   中英

在语言更改时保留 ListPreference 值

[英]Preserving ListPreference value on language change

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

  1. 打开英文应用,select 一个值。 这是保存在数据/数据中的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()
    }
}

首选项.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...) 访问这些值,以与实际偏好值进行比较。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM