Links
Comment on page

In-app language settings

Firework Android SDK introduces the following API for app level language settings. To help host apps provide a better experience for users who set their system language to one but use the other language for a particular app.

In-app language settings API

Support version: v5.14.12
/**
* @param baseContext activity context to apply locale changes.
* @param prefLocal the new specified in-app locale
*
**/
fun changeAppLocale(baseContext: Context, prefLocale: String)

Example code snippet

In the host app activity, it designs a way to adapt new locale changes by applying the locale configuration changes to the Activity. Also, call FwSDK.changeAppLocale(baseContext: Context, prefLocale: String) with a language code to apply the new locale to Firework Android SDK.
class MainActivity : AppCompatActivity() {
...
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(updateBaseContextLocale(newBase))
}
private fun updateBaseContextLocale(context: Context): Context? {
val persistLocale = getLocalePreference(context)
persistLocale?.let{
val localeStrings = it.split("-")
val locale = if (localeStrings.size > 1) {
Locale(localeStrings[0], localeStrings[1])
} else {
Locale(it)
}
Locale.setDefault(locale)
return updateResourcesLocale(context, locale)
}
val locale = Locale(persistLocale)
Locale.setDefault(locale)
return updateResourcesLocale(context, locale)
}
private fun updateResourcesLocale(context: Context, locale: Locale): Context {
val resources = context.resources
val configuration = resources.configuration
configuration.setLocale(locale)
configuration.setLayoutDirection(locale)
return context.createConfigurationContext(configuration)
}
private fun setLocalePreference(language: String) {
val pref = getSharedPreferences(PREF_LANGUAGE,Context.MODE_PRIVATE)
pref.edit().putString(KEY_LANGUAGE,language).apply()
//Call changeAppLocale() API to set your preferred language to Firework Android SDK.
FwSDK.changeAppLocale(this, language)
}
private fun getLocalePreference(context: Context) : String? {
val pref = context.getSharedPreferences(PREF_LANGUAGE, Context.MODE_PRIVATE)
return pref.getString(KEY_LANGUAGE, "en")
}
...
//Switching app language by clicking the option menu
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.locale_en -> {
setLocalePreference("EN")
recreate()
true
}
R.id.locale_ar -> {
setLocalePreference("AR")
recreate()
true
}
R.id.locale_jp -> {
setLocalePreference("ja-JP")
recreate()
true
}
else -> {
false
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_activity_actions, menu)
return true
}
...
}
See the results in the below demo video:
In-app-language-settings-demo.mp4
25MB
Binary