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