Skip to content
Related Articles

Related Articles

Improve Article

How to Change the Whole App Language in Android Programmatically?

  • Last Updated : 06 Jan, 2021

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.

Example

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.

XML




<resources>
    <string name="app_name">GFG | Change App Language</string>
    <string name="selected_language">हिन्दी</string>
    <string name="language">नमस्ते, जी यफ जी</string>
</resources>

And in string.xml file which is the default for English add these line.

XML






<resources>
    <string name="app_name">GFG | Change App Language</string>
    <string name="selected_language">English</string>
    <string name="language">Hi, GFG</string>
</resources>

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. 

XML




<resources
    <color name="colorPrimary">#0F9D58</color
    <color name="colorPrimaryDark">#16E37F</color
    <color name="colorAccent">#03DAC5</color
</resources

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.

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
      
    <!--text view for the message to display-->
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="48dp"
        android:text="Welcome To GeeksForGeeks"
        android:textAlignment="center" />
  
    <!--button view for hindi language-->
    <Button
        android:id="@+id/btnHindi"
        android:layout_margin="16dp"
        android:background="@color/colorPrimary"
        android:textColor="#ffffff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hindi"/>
  
    <!--button view for english language-->
    <Button
        android:id="@+id/btnEnglish"
        android:layout_margin="16dp"
        android:background="@color/colorPrimary"
        android:textColor="#ffffff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="English"/>
  
</LinearLayout>

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.

Java




import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;
  
import java.util.Locale;
  
public class LocaleHelper {
        private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";
  
        // the method is used to set the language at runtime
        public static Context setLocale(Context context, String language) {
            persist(context, language);
  
            // updating the language for devices above android nougat
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                return updateResources(context, language);
            }
            // for devices having lower version of android os
            return updateResourcesLegacy(context, language);
        }
  
        private static void persist(Context context, String language) {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString(SELECTED_LANGUAGE, language);
            editor.apply();
        }
  
        // the method is used update the language of application by creating
        // object of inbuilt Locale class and passing language argument to it
        @TargetApi(Build.VERSION_CODES.N)
        private static Context updateResources(Context context, String language) {
            Locale locale = new Locale(language);
            Locale.setDefault(locale);
  
            Configuration configuration = context.getResources().getConfiguration();
            configuration.setLocale(locale);
            configuration.setLayoutDirection(locale);
  
            return context.createConfigurationContext(configuration);
        }
  
  
        @SuppressWarnings("deprecation")
        private static Context updateResourcesLegacy(Context context, String language) {
            Locale locale = new Locale(language);
            Locale.setDefault(locale);
  
            Resources resources = context.getResources();
  
            Configuration configuration = resources.getConfiguration();
            configuration.locale = locale;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                configuration.setLayoutDirection(locale);
            }
  
            resources.updateConfiguration(configuration, resources.getDisplayMetrics());
  
            return context;
        }
    }

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.

Java




import androidx.appcompat.app.AppCompatActivity;
  
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
  
public class MainActivity extends AppCompatActivity {
    TextView messageView;
    Button btnHindi, btnEnglish;
    Context context;
    Resources resources;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // referencing the text and button views
        messageView = (TextView) findViewById(R.id.textView);
        btnHindi = findViewById(R.id.btnHindi);
        btnEnglish = findViewById(R.id.btnEnglish);
  
        // setting up on click listener event over the button
        // in order to change the language with the help of 
          // LocaleHelper class
        btnEnglish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context = LocaleHelper.setLocale(MainActivity.this, "en");
                resources = context.getResources();
                messageView.setText(resources.getString(R.string.language));
            }
        });
  
        btnHindi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context = LocaleHelper.setLocale(MainActivity.this, "hi");
                resources = context.getResources();
                messageView.setText(resources.getString(R.string.language));
            }
        });
  
    }
}

Output:

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!



My Personal Notes arrow_drop_up
Recommended Articles
Page :