静态资源位置
- res/values-*
方案A,会重建Activity
- 新建locales_config.xml
<?xml version="1.0" encoding="utf-8"?>
<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 列出你的应用支持的所有语言,按你希望的顺序 -->
<locale android:name="zh-CN" />
<locale android:name="en-US" />
<!-- 如果有更多语言,继续添加 -->
</locale-config>- AndroidMainfest.xml中引用
<application
android:localeConfig="@xml/locales_config"
... >
<activity android:name=".MainActivity" ... />
</application>- 确保使用AppCompatActivity,并调用代码
val locale = Locale.US
val locales = LocaleListCompat.forLanguageTags(locale.toLanguageTag())
AppCompatDelegate.setApplicationLocales(locales)
recreate()- 注意 Activity必须继承AppCompatActivity
方案B,针对局部,临时预览或持久化
提供临时的context,防止重建
CompositionLocalProvider(
LocalContext provides newContext,
LocalConfiguration provides newConfig
){
Text(LocaleText(R.string.loading))
Button({
coroutine.launch {
currentLocale = Locale.US
}
}) {
Text("English")
}
}
fun LocaleText(@StringRes id: Int): String{
val config = LocalConfiguration.current
val context = LocalContext.current
val localizedContext = context.createConfigurationContext(config)
return localizedContext.getString(id)
}