UI android 的翻译(在 Kotlin 中)

Translation of UI android (in Kotlin)

我需要使用 Kotlin 翻译我的 UI(针对 Android)。 我使用了这段代码(每次用户 运行 应用程序):

    val sharedPref: SharedPreferences = getSharedPreferences(UI_LANGUAGE_CHANGED, PRIVATE_MODE)
    var restart: Boolean = sharedPref.getBoolean(UI_LANGUAGE_CHANGED, true)

    var lang = selectedLanguageVar.split("-")[0]
    if (translations_languages.indexOf(lang) == -1) {
        lang = "en"
    }
    //println("-->sel: " + selectedLanguageVar + " -->lang: " + getString(R.string.language))
    //println("-->index: " + translations_languages.indexOf(lang))
    var locale: Locale = Locale(lang)
    Locale.setDefault(locale)
    var res: Resources = resources
    var config: Configuration = res.configuration
    config.setLocale(locale)
    //config.setLayoutDirection(locale)
    //createConfigurationContext(config)
    resources.updateConfiguration(config, resources.displayMetrics)

    if (restart || type == "restart") {
        val intent = Intent(this, RestartActivity::class.java).also {
            startActivity(it)

            finish()
        }
    } else {
        if (type == "start") {
            val intent = Intent(this, RestartActivity::class.java).also {
                startActivity(it)
            }
        }
    }

但是当我安装应用程序时它是一种设备语言,它被翻译成 selected 语言。因此,例如,我安装了该应用程序,并且在我的设备上有英语和法语。如果我 select 这两种语言中的一种,它翻译正确,否则它不起作用。

我也试过 createConfigurationContext(config) 但它不起作用。有没有办法始终翻译 selected 语言(独立于设备)?

如评论中所述,更改语言取决于您支持的 API 级别。自 API 23.

以来,我们公司也是这样做的

我们通过包装我们拥有的单个 activity 的上下文来做到这一点。在这里,我将其更改为法语,但您必须决定使用哪个语言环境。我认为这部分取决于你的用例,所以我会把它从这个答案中去掉。每次您想要更改语言时都需要重新创建 activity。这可以通过获取 activity 的实例并在其上发出 recreate() 来轻松完成。

class BaseActivity : AppCompatActivity() {

  override fun attachBaseContext(newBase: Context) {
    super.attachBaseContext(newBase.wrap(Locale.FRENCH))
  }
}

包装上下文的方法是一个扩展函数,写成这样:

fun Context.wrap(desiredLocale: Locale): Context {
  if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M)
    return getUpdatedContextApi23(desiredLocale)

  return if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N) 
      getUpdatedContextApi24(desiredLocale) 
    else 
      getUpdatedContextApi25(desiredLocale)
}

以下是根据版本更新语言环境的每种方法:

@TargetApi(Build.VERSION_CODES.M)
private fun Context.getUpdatedContextApi23(locale: Locale): Context {
  val configuration = resources.configuration
  configuration.locale = locale
  return createConfigurationContext(configuration)
}

private fun Context.getUpdatedContextApi24(locale: Locale): Context {
  val configuration = resources.configuration
  configuration.setLocale(locale)
  return createConfigurationContext(configuration)
}

@TargetApi(Build.VERSION_CODES.N_MR1)
private fun Context.getUpdatedContextApi25(locale: Locale): Context {
  val localeList = LocaleList(locale)
  val configuration = resources.configuration
  configuration.locales = localeList
  return createConfigurationContext(configuration)
}