Created
June 14, 2020 09:37
-
-
Save agarasul/5bf58b5e7cf66f7d70203bf9dc15f439 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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