我正在尝试使用LocaleManager更改应用程序中的语言。我的代码可以在Nougat和Oreo上完美运行,但不能在棉花糖上运行。我有一个设置活动,在其中添加了一个对话框来更改语言。这是我的代码:
LocaleManager.kt:
class LocaleManager {
companion object {
val LANGUAGE_ENGLISH = "en"
private val LANGUAGE_KEY = "display_lang"
fun setNewLocale(c: Context, language: String): Context {
persistLanguage(c, language)
return updateResources(c, language)
}
private fun persistLanguage(c: Context, language: String) {
val prefs = PreferenceManager.getDefaultSharedPreferences(c)
prefs.edit().putString(LANGUAGE_KEY, language).apply()
}
private fun updateResources(context: Context, language: String): Context {
val locale = Locale(language)
Locale.setDefault(locale)
val config = Configuration(context.resources.configuration)
config.setLocale(locale)
return context.createConfigurationContext(config)
}
fun setLocale(c: Context): Context {
return updateResources(c, getLanguage(c))
}
fun getLanguage(c: Context): String {
val prefs = PreferenceManager.getDefaultSharedPreferences(c)
return prefs.getString(LANGUAGE_KEY, LANGUAGE_ENGLISH)
}
}
}
这是我的 Setting Activity.kt (自定义对话框):
fun showChangeLangDialog() {
val factory = LayoutInflater.from(this)
val langDialog = factory.inflate(R.layout.select_lang_dialog, null)
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")
Log.e("Lan", LocaleManager.getLanguage(this))
if (LocaleManager.getLanguage(this) == obj.getString("code")) {
rdbtnLang.isChecked = true
}
rdbtnLang.textSize = 20f
rdbtnLang.setPadding(20, 30, 30, 30)
langDialog.selectLangList.addView(rdbtnLang)
}
AlertDialog.Builder(this)
.setTitle(R.string.selectLang)
.setPositiveButton(R.string.ok) { dialog, i ->
langList.forEach {
val obj = JSONObject(it)
if (langDialog.selectLangList.checkedRadioButtonId == obj.getInt("id")) {
setNewLocale(obj.getString("code"))
}
}
dialog.dismiss()
}
.setNegativeButton(R.string.cancel) { dialog, whichButton ->
dialog.dismiss()
}
.setView(langDialog)
.create()
.show()
}
在每个需要更改语言文本的活动中,我都添加以下代码段:
override fun attachBaseContext(base: Context) {
super.attachBaseContext(LocaleManager.setLocale(base))
}
答案 0 :(得分:1)
我认为您必须将字符串类型“ gu-rIN
”转换为简单的“ gu
”类型翻译