Skip to content

Instantly share code, notes, and snippets.

@agarasul
Created June 14, 2020 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agarasul/5bf58b5e7cf66f7d70203bf9dc15f439 to your computer and use it in GitHub Desktop.
Save agarasul/5bf58b5e7cf66f7d70203bf9dc15f439 to your computer and use it in GitHub Desktop.
object LocaleHelper {
private val SELECTED_LANGUAGE = "app_lang"
fun onAttach(context: Context): Context {
val langu = getPersistedData(context, Locale.getDefault().language)
return setLocale(context, langu)
}
fun onAttach(context: Context, defaultLanguage: String): Context {
val langu = getPersistedData(context, defaultLanguage)
return setLocale(context, langu)
}
fun getLanguage(context: Context?): String? {
return getPersistedData(context, Locale.getDefault().language)
}
fun setLocale(context: Context, language: String?): Context {
persist(context, language)
return updateResources(context, language)
}
fun getCurrentLocale(context: Context): Locale {
return Locale(getLanguage(context) ?: Locale.getDefault().language)
}
private fun getPersistedData(context: Context?, defaultLanguage: String): String? {
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
return preferences.getString(SELECTED_LANGUAGE, defaultLanguage)
}
private fun persist(context: Context, language: String?) {
val preferences = PreferenceManager.getDefaultSharedPreferences(context)
val editor = preferences.edit()
editor.putString(SELECTED_LANGUAGE, language)
editor.apply()
}
@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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment