我在Kotlin写了一个应该支持多种语言的Android应用程序。它适用于一个特定的Activity,但我希望它可以在应用程序范围内工作。例如,如果我在“设置活动”中编写本地化代码以更改语言,则它仅适用于“设置活动”而不适用于“其他”。请帮助我改变所有活动的语言。
1)我的更改语言对话框:
fun showChangeLangDialog() {
val factory = LayoutInflater.from(this)
val langDialog = factory.inflate(R.layout.select_lang_dialog, null)
selectedLanguage = SettingsHandler(this).getSettings("display_lang")
val langList = resources.getStringArray(R.array.languages)
langList.forEach {
val obj = JSONObject(it)
val rdbtnLang = RadioButton(this)
rdbtnLang.id = obj.getInt("id")
rdbtnLang.text = obj.getString("lang")
rdbtnLang.textSize = resources.getDimension(R.dimen.radio_text_size)
rdbtnLang.setPadding(20, 30, 30, 30)
langDialog.selectLangList.addView(rdbtnLang)
}
AlertDialog.Builder(this)
.setTitle("Select LanguageGlobal")
.setPositiveButton("Ok") { dialog, i ->
if (langDialog.selectLangList.checkedRadioButtonId > 0) {
settingHandler.updateSettingsViaKey("display_lang", langDialog.selectLangList.checkedRadioButtonId.toString())
}
langList.forEach {
val obj = JSONObject(it)
if (langDialog.selectLangList.checkedRadioButtonId == obj.getInt("id")) {
setLocale(obj.getString("code"))
recreate()
}
}
dialog.dismiss()
}
.setNegativeButton("Cancel") { dialog, whichButton ->
dialog.dismiss()
}
.setView(langDialog)
.create()
.show()
}
2)setLocate()函数:
fun setLocale(lang: String) {
val locale = Locale(lang)
selectedLanguage = SettingsHandler(applicationContext).getSettings("display_lang")
Locale.setDefault(locale)
val config = Configuration()
config.locale = locale
baseContext.resources.updateConfiguration(config, baseContext.resources.displayMetrics)
val editor = getSharedPreferences("settings", Context.MODE_PRIVATE).edit()
editor.putString("My_Lang", lang)
editor.apply()
}