Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Change Input Type of EditText Programmatically in Android?
Next article icon

How to Change the Whole App Language in Android Programmatically?

Last Updated : 06 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 require these Locale to perform a task are called locale-sensitive and use 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.

string.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. 

colors.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.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical"     tools:context=".MainActivity">          <!-- TextView 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.

LocaleHelper.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";      // Method 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 with lower versions 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();     }      // Method to update the language of the application by creating     // an object of the inbuilt Locale class and passing the 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.

MainActivity.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:



Next Article
How to Change Input Type of EditText Programmatically in Android?
author
ankur035
Improve
Article Tags :
  • Android
  • Java
  • Technical Scripter
  • Android Projects
  • Technical Scripter 2020
Practice Tags :
  • Java

Similar Reads

  • How to Change App Icon of Android Programmatically in Android?
    In this article, we are going to learn how to change the App Icon of an App on the Button Click. This feature can be used when we have an app for different types of users. Then as per the user type, we can change the App Icon Dynamically.  Step by Step Implementation Step 1: Create a New Project To
    3 min read
  • How to Change TextView Size Programmatically in Android?
    A TextView in Android is a UI element to display text. It can be programmed in the layout file statically as well as in the main code dynamically. Thus, various attributes of a TextView such as the text, text color, text size, TextView background, and its size can be changed programmatically. In thi
    3 min read
  • How to Change ActionBar Title Programmatically in Android?
    Whenever we develop an Android application and run it, we often observe that the application comes with an ActionBar with the name of the application in it. This happens by default unless explicitly changed. This text is called the title in the application. One can change the title of the applicatio
    3 min read
  • How to Change Input Type of EditText Programmatically in Android?
    EditText in Android UI or applications is an input field, that is used to give input text to the application. This input text can be of multiple types like text (Characters), number (Integers), etc. These fields can be used to take text input from the users to perform any desired operation. Let us s
    3 min read
  • How to Disable Dark Mode Programmatically in Android?
    In this article, we will learn how to disable Dark Mode programmatically in Android. Changing the theme of your app is a simple task that includes changing the code in the XML file. Step by Step Implementation Step 1: Create a New Project in Android Studio Create a new project by clicking on the fil
    2 min read
  • How to Get RAM Memory in Android Programmatically?
    RAM (Random Access Memory) of a device is a system that is used to store data or information for immediate use by any application that runs on the device. Every electronic device that runs a program as a part of its application has some amount of RAM associated with it. Mobile devices nowadays come
    3 min read
  • How to Adjust the Volume of Android Phone Programmatically from the App?
    As stated in the title of this article let's discuss how to adjust the volume of an Android Phone programmatically from the App. Basically, control the volume in the app mean Increase or Decrease the Volume without the Volume Bar UIIncrease or Decrease the Volume with the Volume Bar UIMute or Unmute
    5 min read
  • How to Quit Android Application Programmatically?
    When we want to implement an exit AlertDialog in our android application we have to programmatically exit our android application. In this article, we will take a look at How to Quit the Android application programmatically. We will be adding a button and on clicking on that button we will be closin
    3 min read
  • How to Set an Image as Wallpaper Programmatically in Android?
    Setting wallpaper in Android programmatically is helpful when the application is fetching wallpapers from the API library and asking the user whether to set the wallpaper for the home screen or not. In this article, it's been discussed how to set a sample image as the home screen wallpaper programma
    4 min read
  • How to Change the Screen Orientation Programmatically using a Button in Android?
    Generally, the screen orientation of any application is Portrait styled. But when it comes to gaming or any other multimedia service such as watching a video, the screen orientation must change functionally from Portrait to landscape or vice-versa when the functionality is not required. So a develop
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences