Мое приложение поддерживает 2 языка: английский sh и испанский sh. Если мой язык устройства - Engli sh, а язык приложения - испанский sh, и я получаю язык по умолчанию как Locale.getDefault().language
, но я получаю испанский sh - я перезагружаю свое приложение. Вот мое приложение
override fun attachBaseContext(base: Context?) {
base?.let {
var user = AppSharedPreference.getUser(it)
if (user == null)
super.attachBaseContext(LocaleUtil.onAttach(it))
else
super.attachBaseContext(LocaleUtil.onAttach(it, user.language))
}
}
Вот мое LocaleUtil
объект LocaleUtil {
// set device locale as default locale of app
fun onAttach(context: Context): Context {
val lang = getPersistedData(context, Locale.getDefault().language)
return setLocale(context, lang)
}
// set given locale as default locale of app
// call if you want to set default locale other than device's locale
fun onAttach(context: Context, defaultLanguage: String): Context {
val lang = getPersistedData(context, defaultLanguage)
return setLocale(context, lang)
}
// call it you want to get saved locale
fun getLanguage(context: Context): String? {
return getPersistedData(context, Locale.getDefault().language)
}
// call if you want to change app's locale
fun setLocale(context: Context, language: String?): Context {
persist(context, language)
return updateResourcesLegacy(context, language)
}
private fun getPersistedData(context: Context, defaultLanguage: String): String? {
return AppSharedPreference.getUserLocale(context)
}
private fun persist(context: Context, language: String?) {
AppSharedPreference.setUserLocale(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)
}
@SuppressWarnings("deprecation")
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
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLayoutDirection(locale)
}
resources.updateConfiguration(configuration, resources.displayMetrics)
return context
}
}