kotlin 如何以编程方式更改Android应用程序区域设置

wa7juj8i  于 2023-03-03  发布在  Kotlin
关注(0)|答案(2)|浏览(118)

在2023年,以编程方式更改应用程序区域设置的正确解决方案是什么?我尝试过不同的方法,但都不起作用。这是我找到的解决方案之一,但它不起作用。object LocaleHelper {

fun setLocale(context: Context, language: String): Context {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        updateResources(context, language)
    } else {
        updateResourcesLegacy(context, language)
    }
}

private fun updateResources(context: Context, language: String): Context {
    val locale = Locale(language)
    Locale.setDefault(locale)
    val configuration = Configuration(context.resources.configuration)
    configuration.setLocale(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
}

}

override fun attachBaseContext(newBase: Context) {
    super.attachBaseContext(LocaleHelper.setLocale(newBase, "kk"))
    }

    val newContext = LocaleHelper.setLocale(this, "kk")
    ActivityCompat.recreate(this)

参考资料中有翻译成其他语言的版本。请告诉我如何更改应用程序中的语言环境

cbeh67ev

cbeh67ev1#

我认为这是一个可能的解决办法。
在您的活动中:

override fun attachBaseContext(newBase: Context?) {
    val newConfiguration = Configuration(newBase?.resources?.configuration).apply {
        setLocale(Locale("kk"))
    }
 
    super.attachBaseContext(newBase?.createConfigurationContext(newConfiguration))
}

如果希望在运行时切换语言,请不要忘记调用Activity.recreate()

4nkexdtk

4nkexdtk2#

试试这个:
public void setLanguage(上下文elContexto,区域设置myLocale){

Locale.setDefault(myLocale);

    Resources res = context.getResources();

    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = myLocale;
    res.updateConfiguration(conf, dm);
}

你叫它:
setLanguage(获取应用程序上下文(),新建区域设置("us"));
然后,重置应用程序。

相关问题