Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.