2

I am trying to change my device's language in my app. I have this code:

Locale locale = new Locale("en_US"); 
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getApplicationContext().getResources().updateConfiguration(config, null);
Log.i("some","Well, I tried!");

But this code does not change state of my device, and in LogCat I can see "Well, I tried" message. What are the possible reasons of such strange behaviour?

Mykhailo Granik
  • 368
  • 8
  • 23

3 Answers3

1

Edit this line

getApplicationContext().getResources().updateConfiguration(config, null);

like this:

context.getApplicationContext().getResources().updateConfiguration(config, null);
Avijit
  • 3,834
  • 4
  • 33
  • 45
1

If you came here for language problems for builds after Summer 2021, it may have nothing to do with your code. We had the same issue and the problem was the new bundle (.aab) requirement (required since Summer 2021).

With app bundles, devices download only the code and resources they require to run your app. So, for language resources, a user’s device downloads only your app’s language resources that match the one or more languages currently selected in the device’s settings. Read further

Basically, the language file is not downloaded if the device does not support that language. There are 2 ways to solve it:

Option 1 (Easiest): Just disable the bundle optimization

Add this in your build.gradle file:

android {
    bundle {
        language {
            enableSplit = false
        }
    }
// ...
// Other configuration
}

Option 2: Download the language file on demand

Use the method described here.

How to debug

Before applying these methods,

  1. Delete the app
  2. Add the new language in the device settings
  3. Download the app again

If the app supports the new language then the problem is definitely the bundle optimization and the above mentioned solutions will work.

Rufat Mirza
  • 1,425
  • 14
  • 20
0

To change the applications locale manually.

You will need to set the locale using the code below.

Locale locale = new Locale("AR"); // AR here is for arabic
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, 
getBaseContext().getResources().getDisplayMetrics());

Make sure it is set in the activity "onCreate" method before calling the "setContentView" method.

Also see that the resource files are specified for the language required.

agomes
  • 331
  • 2
  • 8