Supporting multiple languages in android app is one of the most important tasks. Try to do it from the beginning otherwise you will end up with lots of strings to translate by the end. If you are not in a habbit of writing each and every string in strings.xml file then you probably should start doing that because it is easier to manage translations that way. We will see that how it is possible to do so.
Create a new android app project. Just like you normally would. I ain’t gonna tell you how to do that. In that open up strings.xml file and one thing I found very useful in new Android studio is that it has an inbuilt translation editor which is pretty useful. Before opening the translation editor, open your strings.xml file and write some strings in it. (Showing support for hindi in this tutorial)
Add more if you want to. Now see the image below, the translation editor looks like this.
In that you have buttons for Add key and Add Locale. Click Add Locale and select the language you wish to translate the strings to. Like I selected Hindi, so mine looks like that. What it basically does is that in res/ folder of the project, it creates values-hi folder. In that there is strings.xml file specifically having all the translated strings for that particular language. The keys will remain the same. Now let us quickly write translations for it. I prefer to use the editor initially. Order does not matter. If you want to copy/paste just to try, open strings.xml file in res/values-hi/ folder and add the following.
Next we add items to menu in which one would be used to show custom language selection dialog. Create new file in res/menu/ called menu_main.xml.
Before we move onto the java part, let us quickly create a custom dialog layout with a spinner in it to select our languages from.
Now in your package, create a new blank activity called MainActivity and add following code in it.
In onOptionsItemSelected(MenuItem item) add the following,
Now add the following method after onOptionsItemSelected(),
Now the most important part is how to read from the preferences and get the correct language. Add in onCreate()
Now run the app, open menu and select language change, you will see a dialog popup. Select the language and click “Change”. It will recreate the activity and use all available translations. Also, it will apply those changes to SharedPreferences so that next time someone opens the app, they will see the last selected language.
That’s all. If you have any questions, post them below.