- Android App-Specific Language Change Programmatically Using Kotlin
- LanguageChooseActivity → MainActvity
- Conversion By Translation: Changing Your Android App Language At Runtime
- The Problem
- Prerequisite
- Configuration Class
- Locale.setDefault() Method
- The Solution
- A Game of Cat & माउस्
- #1: System Language Change
- #2: WebView
- Conclusion
- Android Building Multi-Language Supported App
- 1. How String Localization Works
- Don’ts:
- 2. Creating New Project
- 3. Testing The Other Languages
- 4. Android Localization Language ISO Codes
- 5. Translation Services
Android App-Specific Language Change Programmatically Using Kotlin
By default, Android will try to load resources based on the System language that is set on the user’s phone. Therefore, if a Tamil language user, Kavi, with her Android set to the Tamil language opened our android application on her phone, she’d see an app localized to her own language.
But what if another user wants to use the Tamil language for his android application on an Android that has its default language set to English?
To deal with this, we will have to programmatically update the locale of our android application to override the default locale set in the user’s system. Here we gonna do ask the user to choose the language and switch the language in application only.
Let’s start with creating new resource files for the Tamil language using Android Studio’s resource file wizard.
Firstly, right-click on the res folder and choose “New -> Android resource file”: It will show prompt like this type file name as strings.xml
Here select the language,
It will generate XML for you then you can put sample string like below.
English default look like
Newly added Langauge Tamil look like
That’s it we configured strings locale.
Now let’s create a ContextUtils utility class to hold our locale updating methods. Place this within a utils package on the android application, as follows:
- Configuration.localethe field was deprecated in API level 24 (Nougat). This was put in place by Android API developers to make coders move to the use of getters and setters instead of directly accessing variables.
- This was marked as the preferred way of setting up locales (instead of using the direct accessor or setLocale(java.util.Locale)) starting from API level 24.
- Before API level 24, developers could directly access the configuration.locale field to change it as they pleased.
Then we can use this method to apply locale changes.
Create BaseActivity which is extends AppCompatActivity and it must be inherited by other activities.
We going to use attachBaseContext override method to update locale configuration to ACTIVITY so it will reflect on all other activities which are extended by.
Q: What is the use of AttachBaseContext?
A: The attachBaseContext function of the ContextWrapper class is making sure the context is attached only once. ContextThemeWrapper applies theme from application or Activity which is defined as android:theme in the AndroidManifest.xml file. Since both Application and Service do not need theme, they inherit it directly from ContextWrapper . During the activity creation, application and service are initiated, a new ContextImpl object is created each time and it implements functions in Context .
LanguageChooseActivity → MainActvity
Here we store inside SharedPreference a string that contains language code like for tamil →“ta” , English →”en”, Hindi →”hi” etc…
This code used to identify the Language using Locale(«language-code»)
After applying in base activity wherever the strings are used automatically translated.
Below is the sample activity that extends BaseActivity().
Just extends BaseActivity is enough and see the magic. 😉 Hope user won’t get lost in application.
Источник
Conversion By Translation: Changing Your Android App Language At Runtime
You have an awesome app with lots of cool features, one of which is multi-language support for your users. Everything works great but your Product Manager wants to improve conversion by prompting users to choose the app’s language on the first launch as part of the onboarding process.
With a couple of years of Android experience under your belt, you’re thinking,
“How hard can it be?”
The Problem
On Android, there is no official support, documentation or API to change an entire app’s language at runtime. When a user opens an app, the resource framework automatically selects the resources that best match the device language settings. In Google Maps, for example, you can not change the street names on the map without changing the entire device language.
Prerequisite
In order to change an app’s language (or Locale in Android terms), we need to be familiar with 2 different mechanisms that will help us achieve our goal:
Configuration Class
This class describes all device configuration information that can impact the resources the application retrieves. This includes user-specified configuration options (locale list and scaling)
Basically, this is the class that Android is gettings its Locale information from.
Overriding this class with the Locale that represents the user’s selected language will change the folder Android is looking for its resources (e.g strings.xml).
Locale.setDefault() Method
Gets the current value of the default locale for this instance of the Java Virtual Machine.
The Default Locale is usually used when using operations like formatting text, parsing numbers or handling dates. So it is important to override it, otherwise, an app may be displayed in the correct language but things like dates and currency will be broken.
The Solution
From API 17 and above, the preferred way to override a Configuration is by wrapping the currently used Context in a new Context using the method below:
We can combine all the actions we need to take into a single function:
This method should be called inside the attachBaseContext() method in the Application class and in each Activity.
As far as the Android system implementation goes, we are done!
(or so I thought? more on that later)
A few things you should do in order to achieve this:
- The selected language should be persisted in Room/SharedPreferences/etc in order to retrieve it later ( CreateLocaleFromSavedLanguage() method in the snippet above)
- Reflect the language change by re-creating your Activity or Fragment (this will result in calling attachBaseContext() and modifying the current Context )
- Optional: Load fresh data from the server based on the selected language, like translated strings or specific business logic directed to the selected language users
A Game of Cat & माउस्
The feature is done and you confidently mark it as ready for QA testing. 💪
As the days pass, bug tickets pile up, each with a different scenario that made the app look like it is partially translated to the selected language and partially using the device language.
Below are 2 example scenarios, there are probably more weird cases, so keep that in mind if you decide to go on this road.
#1: System Language Change
If the user changes the device’s main language while your app is in the background, your app Locale will be overridden by the Android system to reflect the new system language.
The fix, in this case, is to override the onConfigurationChanged() method in the Application class and override the Locale using the updateConfiguration() method found in Resource class.
#2: WebView
If your app is using WebView in order to display web pages (yeah I hate it too) then you will notice strange behavior every time a WebView is used.
After each WebView creation, the Application Locale gets overridden with the system Locale which messed up the translations. 🤔
The reason behind this is starting with Android N, the Chrome app will be used to render any/all Webviews in third-party Android apps. Because Chrome is an Android app in itself, running in its own sandboxed process, it will not be bound to the Locale set by your app. Instead, Chrome will revert to the primary device Locale .
Source: https://stackoverflow.com/a/40675539/5516215
The fix, in this case, is again to override the Locale after a WebView is created using the technique we wrote above. One way of doing this is by using a custom WebView :
Hopefully, this issue should be resolved in Android 10, where the Chrome app will no longer be the WebView provider.
Source: https://www.xda-developers.com/google-chrome-no-longer-webview-provider-android-10/
Conclusion
After a few iterations, everything looks good. The Product Manager is happy, your users are happy and even you feel quite pleased with implementing a feature that is not officially supported. 👏
With that said, future Android versions can change how this solution affects your app and even introduce new edge cases that require special care, it is up to you to decide if the investment is worthwhile.
Источник
Android Building Multi-Language Supported App
Android is one of the few popular mobile operating systems having millions of users over 190 countries and growing day by day. So when you are aiming your app to be globally successful, it is always a good idea to make the app localized.
While localizing, you should consider using appropriate text, audio, currency, numbers and graphics depending upon the region or country. But this tutorial only covers localizing strings i.e supporting multiple languages. Localizing with Resources explains about other things should be considered when localizing your app.
In this article we are going to build a Multi-Language supported app that supports French, Deutsch (German), Hindi and Japanese.
VIDEO DEMO
1. How String Localization Works
By default android considers English as primary language and loads the string resources from res ⇒ values ⇒ strings.xml. When you want to add support for another language, you need to create a values folder by appending an Hyphen and the ISO language code. For example if you want to add support for French, you should create a values folder named values-fr and keep a strings.xml file in it with all the strings translated into French language.
In brief the localization works as follows
1. When user changes the device language through Settings ⇒ Language & Input, android OS itself checks for appropriate language resources in the app. (Let’s say user is selecting French)
2. If the app supports selected language, android looks for it’s string resources in values-(ISO language Code) folder in the project. (For french it loads the string values from values-fr/string.xml)
3. If the supported language strings.xml misses any string value, android always loads the missing strings from default strings.xml file i.e values/strings.xml
So it is mandatory that the default stings.xml file should contains all the string values that app uses. Other wise the app will crash with Force Close error.
While you are supporting multiple languages, you should consider below as a best practice while defining the strings. Always declare the string in strings.xml only.
When referring it in xml, use @strings notation.
When defining the string through java code, use R.string
Don’ts:
Never hard code the string in xml or in java code which make the translation difficult.
So let’s create a new project and try with an example.
2. Creating New Project
1. Create a new project in Eclipse by going to File ⇒ New ⇒ Android Application Project and fill the required information.
2. Add following colors in colors.xml located under values. If you don’t see colors.xml, create a new file and add the below colors.
3. Under drawable folder create three files named bg_button_rounded.xml,bg_form_rounded.xml, bg_gradient.xml with following contents. These files are not related to language support, but just to give nice gradients background and rounded corners to buttons, input boxes.
bg_button_rounded.xml
bg_form_rounded.xml
bg_gradient.xml
4. Open strings.xml located under values folder and add following strings. These are default English language strings.
5. Now under res folder create three folders named values-de, values-fr, values-hi, values-ja and a strings.xml file in each of the folders.
Your project should look like this once you created the required files/folders.
Now translate the strings into respected languages and place them in appropriate strings.xml files.
Deutsch values-de/strings.xml
Hindi values-hi/strings.xml
Japanese values-ja/strings.xml
6. Open your main activity layout file (in my case activity_main.xml) and add the following content to create a simple layout. This layout contains a title and a login form.
7. Open your MainActivity.java and make sure that it has following code. This code will be added automatically when you create new project.
Now if you run the project you should see the app in English (assuming that your device is set to English language)
3. Testing The Other Languages
In order to see the app in other languages follow below steps or check the above demo video.
1. On the device go to Settings ⇒ Language & Input
2. Select the Language and choose the language that you supported in the app.
4. Android Localization Language ISO Codes
Below table give you ISO languages codes for all the languages that android supports.
Language | Locale | values/strings.xml |
German | de | values-de/strings.xml |
Chinese | zh | values-zh/strings.xml |
Czech | cs | values-cs/strings.xml |
Dutch | nl | values-nl/strings.xml |
French | fr | values-fr/strings.xml |
Italian | it | values-it/strings.xml |
Japanese | ja | values-ja/strings.xml |
Korean | ko | values-ko/strings.xml |
Polish | pl | values-pl/strings.xml |
Russian | ru | values-ru/strings.xml |
Spanish | es | values-es/strings.xml |
Arabic | ar | values-ar/strings.xml |
Bulgarian | bg | values-bg/strings.xml |
Catalan | ca | values-ca/strings.xml |
Croatian | hr | values-hr/strings.xml |
Danish | da | values-da/strings.xml |
Finnish | fi | values-fi/strings.xml |
Greek | el | values-el/strings.xml |
Hebrew | iw | values-iw/strings.xml |
Hindi | hi | values-hi/strings.xml |
Hungarian | hu | values-hu/strings.xml |
Indonesian | in | values-in/strings.xml |
Latvian | lv | values-lv/strings.xml |
Lithuanian | lt | values-lt/strings.xml |
Norwegian | nb | values-nb/strings.xml |
Portuguese | pt | values-pt/strings.xml |
Romanian | ro | values-ro/strings.xml |
Serbian | sr | values-sr/strings.xml |
Slovak | sk | values-sk/strings.xml |
Slovenian | sl | values-sl/strings.xml |
Swedish | sv | values-sv/strings.xml |
Tagalog | tl | values-tl/strings.xml |
Thai | th | values-th/strings.xml |
Turkish | tr | values-tr/strings.xml |
Ukrainian | uk | values-uk/strings.xml |
Vietnamese | vi | values-vi/strings.xml |
5. Translation Services
Right now I used Google Translate service to translate the strings into other languages. But if you want more accurate and meaningful translation always go for professional services like Professional translations through Google Play
Finally Localization Checklist gives you list of things to be verified before the app goes live when localization considered.
Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: [email protected]
Источник