如何使用 Jetpack Compose 实现应用内本地化

Far*_*qui 5 android localization android-jetpack-compose

如何使用 Jetpack Compose 实现应用内本地化?我的意思是我不希望用户更改他们的设备语言,而是让他们仅更改应用程序语言。如何实现这一目标?我找到的所有资源都谈到了更改设备语言。

ngl*_*ber 3

处理应用程序国际化的推荐方法是使用“每应用程序语言”功能。

您可以在这里找到更多信息: https://www.youtube.com/watch ?v=DUKnNWwcNvo

[之前的回答]

这就是我根据这里的答案所做的。

在您的应用程序类中,执行以下操作:

class MyApp : Application() {
    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(LocaleHelper.setLocale(base, myLang))
    }

    companion object {
        var myLang = "en"
    }
}
Run Code Online (Sandbox Code Playgroud)

我将语言保存在myLang变量中,但实际上您将保存在Shared Preferences中。

onAttachBaseContextsetLocale调用(它在下面声明)。

然后,在您的活动中您将执行相同的操作:

class MainActivity : AppCompatActivity() {
    override fun attachBaseContext(newBase: Context) {
        super.attachBaseContext(
            LocaleHelper.setLocale(newBase, MyApp.myLang)
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

下面的对象将设置语言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
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,在您的可组合项中,您可以执行以下操作:

@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))
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,调用该recreate方法是为了重新创建当前活动并应用语言更改。