为了确保您的应用程序的语言可以在运行 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>
Run Code Online (Sandbox Code Playgroud)
如果我们还想在应用程序的设置中提供自定义区域设置选择器,我们如何检索支持的区域设置列表以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)
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
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
}
}
Run Code Online (Sandbox Code Playgroud)
需要Appcompat 1.6.0-beta01 或更高版本
| 归档时间: |
|
| 查看次数: |
1152 次 |
| 最近记录: |