Change The Android App Language Using Locale Kotlin Android 13 With Backward Compatability
Why do we need app localization?
Android runs on many devices in many regions. To reach the most users, make sure that your app handles text, audio files, numbers, currency, and graphics in ways appropriate to the locales where your app is used.
If you are using Jetpack Compose don’t forget to extend MainActivity using AppCompatActivity
Step-by-step guide
Add Dependency in build.gradle (app-level)
implementation 'androidx.appcompat:appcompat:1.6.1'
Make Locale File In res/xml/locales_config.xml
Add Languages Of Your Choice
<?xml version="1.0" encoding="utf-8"?>
<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
<locale android:name="en" />
<locale android:name="es" />
<locale android:name="fr" />
<locale android:name="ja" />
<locale android:name="zh" />
<locale android:name="hi" />
</locale-config>
Changes AndroidManifest.xml
Add localeConfig attribute in application tag and also add service so that it will preserve state without extra code
this is for Backward Compatibility
<application
...
android:localeConfig="@xml/locales_config"
tools:targetApi="tiramisu"
...>
..........
<service
android:name="androidx.appcompat.app.AppLocalesMetadataHolderService"
android:enabled="false"
android:exported="false">
<meta-data
android:name="autoStoreLocales"
android:value="true" />
</service>
...........
</application>
Kotlin Code
Finally, you can call the function like this on the button clicked or by showing Dialog.
Changing The Language Of the App On Button Click
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.getSystemService(LocaleManager::class.java)
.applicationLocales = LocaleList.forLanguageTags("hi")
} else {
AppCompatDelegate.setApplicationLocales(
LocaleListCompat.forLanguageTags(
"hi"
)
)
}
Fetching Current App Language To Show to The User
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
val currentAppLocales =
context.getSystemService(LocaleManager::class.java)
.applicationLocales
Log.d(TAG, "HomeChatScreen:11 $currentAppLocales")
} else {
val currentAppLocales =
AppCompatDelegate.getApplicationLocales()
Log.d(TAG, "HomeChatScreen:222 $currentAppLocales")
}
Note:: Sometimes you might want to add App localization in existing project it might not work. I had faced same issue.So whenever you encounter issue not reflecting changes. Just make new project and copy your code from Old to New Project.
🚨 Add Below Code In build.gradle🚨
android{
bundle {
language {
enableSplit = false
}
}
}
If this article really helps you Please don’t forget to Clap 👏
You can find the official example from the below link