Internationalizing | localization in the Android app
Android runs on many devices in many regions. To reach the most users, we need to ensure that our app should be accessible in regional locales.
To Localise the app your app must comply with the guide line for string resource file.
e.g.
1) All strings need to be stored in the string.xml file
2) Need to add support for RTL support if you add language that starts reading from right to left.
Once you have completed the above change, you have String.xml with all the strings the app uses.
Step 1: Install the AndroidLocalize plugin this will allow you to translate the string.xml file in the required format.
Step 2: To get the string file you wanted, right-click on the default string.xml file and select “translate to other languages” Then you need to select the language that you want to get the translation.
Step 3:Define and call this method wherever you want to trigger localization.
fun changeLanguage(lang: String) {
val locale = LocaleListCompat.forLanguageTags(lang)
AppCompatDelegate.setApplicationLocales(locale)
}
By calling this method it will update the language and you can now see translated values.
For compose only slight change you need to do additionally.
If you are using it for jetpack compose then you need to define or trigger recomposition manually to reflect the changes.
Approach 1:
To do that you can restart the activity.
Approach 2:
You need to define one variable at the top level of the composition tree and then set its value to do recomposition.
below is an example where I used a variable called screenRefresh and later I set its value to do recomposition.
@Composable
fun Body() {
var screenRefresh by remember {
mutableStateOf(false)
}
Scaffold(topBar = { TopAppBar(title = { Text(text = "") }) })
{
screenRefresh
Column(Modifier.padding(it)) {
Text(text = stringResource(R.string.welcome_to_my_article))
Button(onClick = {
screenRefresh=!screenRefresh
changeLanguage("fr")
}) {
Text(text = "Switch to French")
}
Button(onClick = {
screenRefresh=!screenRefresh
changeLanguage("en")
}) {
Text(text = "Switch to English")
}
Button(onClick = {
screenRefresh=!screenRefresh
changeLanguage("pt")
}) {
Text(text = "Switch to Portugal")
}
}
}
}