How to Change the Whole App Language in Android Programmatically?
Android 7.0(API level 24) provides support for multilingual users, allowing the users to select multiple locales in the setting. A Locale object represents a specific geographical, political, or cultural region. Operations that required these Locale to perform a task are called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation so, the number should be formatted according to the conventions of the user’s native region, culture, or country.
In this example, we are going to create a simple application in which the user has the option to select his desired language-English or Hindi. This will change the language of the whole application. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step by Step Implementation
Step 1: Create A New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Create Resource Files
Reference: Resource Raw Folder in Android Studio
In this step, we are required to create a string resource file for the Hindi language. Go to app > res > values > right-click > New > Value Resource File and name it as strings. Now, we have to choose qualifiers as Locale from the available list and select the language as Hindi from the drop-down list. Below is the picture of the steps to be performed.
Now, In this resource file string.xml(hi) add the code given below in the snippet.
And in string.xml file which is the default for English add these line.
Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes.
Step 3: Create The Layout File For The Application
In this step, we will create a layout for our application. Go to app > res > layout > activity_main.xml and add two TextView, one for the message and one for the language selected, and an ImageView for the drop_down icon. Below is the code snippet is given for the activity_main.xml file.
Step 4: Create LocaleHelper Class
Now, We will create a Locale Helper class. This class contains all the functions which will help in language switching at runtime. Go to app > java > package > right-click and create a new java class and name it as LocaleHelper. Below is the code snippet is given for LocaleHelper class.
Step 5: Working With the MainActivity.java File
In this step, we will implement the Java code to switch between the string.xml file to use various languages. First, we will initialize all the Views and set click behavior on an Alert dialog box to choose the desired language with the help of LocalHelper class. Below is the code snippet is given for the MainActivity.java class.