如何使用Jetpack Compose实现应用程序内本地化?我的意思是,我不希望用户更改他们的设备语言,相反,让他们只更改应用程序语言.如何做到这一点?我找到的所有资源都在谈论改变设备语言.
如何使用Jetpack Compose实现应用程序内本地化?我的意思是,我不希望用户更改他们的设备语言,相反,让他们只更改应用程序语言.如何做到这一点?我找到的所有资源都在谈论改变设备语言.
这是我根据这个答案here做的.
在应用程序类中,执行以下操作:
class MyApp : Application() {
override fun attachBaseContext(base: Context) {
super.attachBaseContext(LocaleHelper.setLocale(base, myLang))
}
companion object {
var myLang = "en"
}
}
我将语言保存在myLang
变量中,但实际上您将保存在Shared Preferences中.
在onAttachBaseContext
中,setLocale
被称为(它在下面声明).
然后,在你的活动中,你也会这样做:
class MainActivity : AppCompatActivity() {
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(
LocaleHelper.setLocale(newBase, MyApp.myLang)
)
}
}
下面的对象将在MyApp.myLang
中设置语言并更新Context
对象.
object LocaleHelper {
fun setLocale(context: Context, language: String): Context? {
MyApp.myLang = language
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context, language);
}
return updateResourcesLegacy(context, language);
}
@TargetApi(Build.VERSION_CODES.N)
private fun updateResources(context: Context, language: String): Context? {
val locale = Locale(language)
Locale.setDefault(locale)
val configuration = context.resources.configuration
configuration.setLocale(locale)
configuration.setLayoutDirection(locale)
return context.createConfigurationContext(configuration)
}
private fun updateResourcesLegacy(context: Context, language: String): Context {
val locale = Locale(language)
Locale.setDefault(locale)
val resources = context.resources
val configuration = resources.configuration
configuration.locale = locale
resources.updateConfiguration(configuration, resources.displayMetrics)
return context
}
}
最后,在composable中,您可以执行以下操作:
@Composable
fun TestLanguage() {
val context = LocalContext.current
Text(text = stringResource(id = R.string.activity_java_text))
Button(onClick = {
LocaleHelper.setLocale(context, "pt")
(context as? Activity)?.recreate()
}) {
Text(text = stringResource(id = R.string.btn_ok))
}
}
注意,调用recreate
方法来重新创建当前活动并应用语言更改.