Android
App Development
Programming
Language Change
Localization

Change app language programmatically in Android

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Changing an app's language programmatically is a requirement that developers often encounter to support multiple locales within Android applications. Users may prefer to use apps in their native language, and providing this feature can greatly enhance the user experience. This article explores how you can achieve this in your Android application, diving into technical explanations and examples.

Android Language Configuration

By default, Android applications use the device's language setting. However, developers can override this and allow users to choose their preferred language directly from within the app. This requires manipulating the application's configuration settings in a way that it reflects the selected language across different sessions.

Implementation Approach

Step 1: Define Multiple Language Resources

Before dynamically changing the app's language, you need to ensure that your app supports multiple languages. This is done by creating resource files for each language:

plaintext
1res/
2  values/
3    strings.xml (default strings)
4  values-es/
5    strings.xml (Spanish strings)
6  values-fr/
7    strings.xml (French strings)

Step 2: Modify Locale Programmatically

To change the app's language programmatically, you need to manipulate the Locale settings. The following code snippet demonstrates how to update the language by modifying the Configuration object:

java
1public void setLocale(Context context, String languageCode) {
2    Locale locale = new Locale(languageCode);
3    Locale.setDefault(locale);
4
5    Resources resources = context.getResources();
6    Configuration config = resources.getConfiguration();
7    config.setLocale(locale);
8
9    // Update application context
10    context = context.createConfigurationContext(config);
11    resources.updateConfiguration(config, resources.getDisplayMetrics());
12}

Step 3: Persist Language Choice

To ensure that the language preference persists across app restarts, you should store the language setting using SharedPreferences:

java
1public void saveLocale(String languageCode) {
2    SharedPreferences prefs = getSharedPreferences("Settings", MODE_PRIVATE);
3    SharedPreferences.Editor editor = prefs.edit();
4    editor.putString("My_Lang", languageCode);
5    editor.apply();
6}
7
8public void loadLocale() {
9    SharedPreferences prefs = getSharedPreferences("Settings", Activity.MODE_PRIVATE);
10    String language = prefs.getString("My_Lang", "");
11    setLocale(this, language);
12}

Step 4: Hook Language Change into UI

To trigger the language change, listen for language selection events, such as a Spinner or Button click event:

java
1languageButton.setOnClickListener(new View.OnClickListener() {
2    @Override
3    public void onClick(View view) {
4        String selectedLanguage = "es"; // For example, Spanish selected
5        setLocale(getApplicationContext(), selectedLanguage);
6        saveLocale(selectedLanguage);
7        recreate(); // This restarts the current Activity to apply the change
8    }
9});

Table: Key Points

Below is a summary of key points to consider when changing app language programmatically:

AspectDescription
Resource SetupDefine strings.xml in values-[lang] folders.
Changing LocaleManipulate Configuration object to set locale.
Persisting Language ChoiceUse SharedPreferences for language persistence.
UI InteractionAttach listeners/handlers to UI elements.
Restarting ActivityCall recreate() to refresh activity with new language.

Challenges and Considerations

  • Strings Consistency: Ensure that all strings have translations to avoid fallback to default language.
  • Runtime Changes: Some locale changes necessitate a restart of activities or even the application to fully take effect.
  • Android Version Differences: Behavior may vary slightly depending on the Android versions; extensive testing is recommended.
  • Locale and Regional Formats: Changing language might also require considering regional formats such as date and currency.

Advanced Considerations

Using ViewModels with Localization

If your app heavily employs ViewModel architecture, localizing within the ViewModel may require similar logic as the Activity or Fragment. Ensure consistent data refresh by observing locale changes within the lifecycle of the ViewModel.

Handling Configuration Changes

With Android 8.0 (API level 26) and above, createConfigurationContext() allows for a more granular handling of Context changes related to configurations including locale. This is crucial when implementing multi-window mode.

Conclusion

Providing users with the ability to switch languages without having to adjust their device language settings is a valuable feature in global applications. By following the steps outlined in this article, you can implement this functionality effectively in your Android app. The key is to ensure localization resources are adequately prepared and that changes persist across app restarts. As Android continues to evolve, keeping abreast of configuration management and localization practices will be paramount to delivering a seamless user experience.


Course illustration
Course illustration

All Rights Reserved.