avatar🐀
霂枯木霂枯木的小站

To witness the sunrise and the sea of blossoms.

行可兼知,而知不可兼行

Android开发国际化(i18n)

静态资源位置 ​

  • res/values-*

方案A,会重建Activity ​

  1. 新建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>
  1. AndroidMainfest.xml中引用
<application
    android:localeConfig="@xml/locales_config"
    ... >
    <activity android:name=".MainActivity" ... />
</application>
  1. 确保使用AppCompatActivity,并调用代码
val locale = Locale.US
val locales = LocaleListCompat.forLanguageTags(locale.toLanguageTag())
AppCompatDelegate.setApplicationLocales(locales)
recreate()
  1. 注意 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)
}
tailscale组网教程
服务器基础安全配置
由 Valaxy v1.2.0 驱动|主题-Yunv1.2.0