Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Class for the runtime switch of localization
// Class for the runtime switch of localization
open class LocalizedActivity : AppCompatActivity() {
override fun attachBaseContext(newBase: Context) {
private fun updateBaseContextLocale(context: Context): Context {
val language = PreferenceManager.getDefaultSharedPreferences(context).getString("languages", Locale.getDefault().language)
val locale = Locale(language)
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
updateResourcesLocale(context, locale)
} else updateResourcesLocaleLegacy(context, locale)
// we want to override default behaviour of home button to make sure it is returning
// to the previous state. We don't have complicated back navigation.
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
// Respond to the action bar's Up/Home button -> {
return true
return super.onOptionsItemSelected(item)
private fun updateResourcesLocale(context: Context, locale: Locale): Context {
val configuration = context.resources.configuration
return context.createConfigurationContext(configuration)
private fun updateResourcesLocaleLegacy(context: Context, locale: Locale): Context {
val resources = context.resources
val configuration = resources.configuration
configuration.locale = locale
resources.updateConfiguration(configuration, resources.displayMetrics)
return context
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.