Skip to content

Instantly share code, notes, and snippets.

@JEuler
Created February 26, 2018 17:03
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 JEuler/9dd1ad8fa76b060262dc02e0378837a9 to your computer and use it in GitHub Desktop.
Save JEuler/9dd1ad8fa76b060262dc02e0378837a9 to your computer and use it in GitHub Desktop.
Class for the runtime switch of localization
// Class for the runtime switch of localization
@SuppressLint("Registered")
open class LocalizedActivity : AppCompatActivity() {
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext((updateBaseContextLocale(newBase)))
}
private fun updateBaseContextLocale(context: Context): Context {
val language = PreferenceManager.getDefaultSharedPreferences(context).getString("languages", Locale.getDefault().language)
val locale = Locale(language)
Locale.setDefault(locale)
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
android.R.id.home -> {
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
@TargetApi(Build.VERSION_CODES.N)
private fun updateResourcesLocale(context: Context, locale: Locale): Context {
val configuration = context.resources.configuration
configuration.setLocale(locale)
return context.createConfigurationContext(configuration)
}
@Suppress("DEPRECATION")
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