App内设置语言主要是靠给Context的configuration设置Locale,API 17以后用context.createConfigurationContext(configuration)方法,API 17以前resources.updateConfiguration(configuration, displayMetrics)。
语言Kotlin
步骤1:更改Configuration
/**更新App内语言*/
fun updateAppLanguage(context: Context): Context {
val locale = Locale(getAppLanguage())//getAppLanguage()返回的时语言简码,中文"zh",英文"en"
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
{
updateAppLanguageOnAPI17(context, locale)
}else {
updateAppLanguageBeforeAPI17(context, locale)
}
}
/**更新App语言,API17以上*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private fun updateAppLanguageOnAPI17(context: Context, locale: Locale): Context{
context.resources.configuration.run {
setLocale(locale)
return context.createConfigurationContext(this)
}
}
/**更新App语言,API17以前*/
private fun updateAppLanguageBeforeAPI17(context: Context, locale: Locale): Context {
context.resources.run {
configuration.locale = locale
updateConfiguration(configuration, displayMetrics)
}
return context
}
步骤2:把更改的Context赋值给Activity
Activity中重写attachBaseContext方法
override fun attachBaseContext(newBase: Context?) {
if (newBase == null) {
super.attachBaseContext(newBase)
} else {
super.attachBaseContext(LanguageManager.updateAppLanguage(newBase))
}
}
注意:Application的Context也需要设置,不然通过ApplicationContext加载出来的文案会没有设置成功
步骤3:记录APP语言
记录APP语言可以用SharePreference存储,当需要切换语言时,先保存需要切换的语言简码,例如中文"zh",英文"en"等,然后调用Activity.recreate()重启页面
网友评论