从Android 13中的区域设置配置中获取区域设置列表



为了确保您的应用程序语言在运行Android 13或更高版本的设备上的系统设置中是可配置的,我们需要创建一个locales_configXML文件,并使用android:localeConfig属性将其添加到我们的应用程序清单中(请参阅此处(。

例如,locales_config.xml可能包含:

<?xml version="1.0" encoding="utf-8"?>
<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
<locale android:name="en"/>
<locale android:name="en-GB"/>
<locale android:name="fr"/>
<locale android:name="ja"/>
<locale android:name="zh-Hans-MO"/>
<locale android:name="zh-Hant-MO"/>
</locale-config>

如果我们还想在应用程序的设置中提供一个自定义的区域设置选择器,我们如何从locales_config.xml中检索支持的区域设置列表,以便填充我们的选择器(而不复制区域设置选择器代码中的列表(?

以下是我用于此目的的kotlin-util类:

LanguageUtil


fun Context.getLocaleListFromXml(): LocaleListCompat {
val tagsList = mutableListOf<CharSequence>()
try {
val xpp: XmlPullParser = resources.getXml(R.xml.locales_config)
while (xpp.eventType != XmlPullParser.END_DOCUMENT) {
if (xpp.eventType == XmlPullParser.START_TAG) {
if (xpp.name == "locale") {
tagsList.add(xpp.getAttributeValue(0))
}
}
xpp.next()
}
} catch (e: XmlPullParserException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
return LocaleListCompat.forLanguageTags(tagsList.joinToString(","))
}

fun Context.getLangPreferenceDropdownEntries(): Map<String, String> {
val localeList = getLocaleListFromXml()
val map = mutableMapOf<String, String>()
for (a in 0 until localeList.size()) {
localeList[a].let {
map.put(it.getDisplayName(it), it.toLanguageTag())
}
}
return map
}

fun setLocale(langTag: String){
val appLocale: LocaleListCompat = LocaleListCompat.forLanguageTags(langTag)
AppCompatDelegate.setApplicationLocales(appLocale)
}

示例用法:

val map = requireContext().getLangPreferenceDropdownEntries()
findPreference<DropDownPreference>("key_lang")?.apply {
entries = map.keys.toTypedArray()
entryValues = map.values.toTypedArray()
onPreferenceChangeListener =  Preference.OnPreferenceChangeListener { _, newValue ->
(newValue as String).let{
value = it
setLocale(it)
}
true
}
}

需要Appcompat 1.6.0-beta01或更高版本的

最新更新