Michael Drdlíček
Michael Drdlíček

Reputation: 539

Change language programmatically in Android

I have multilanguage android app. I need to set different language than user has in device settings. When my app is started, user choose from prefered language. On android 7 and below I use updateconfuguration in my application class. But this solution not work on android 8. I try to use update configuration in attachBaseContext in every activity, but without success.

Upvotes: 3

Views: 5663

Answers (2)

AutonomousApps
AutonomousApps

Reputation: 4389

@codespy has the right idea, but to provide more detail:

I had the exact same issue in my app. I initially thought the problem was using this deprecated method of setting a custom language:

Locale.setDefault(newLocale);
Configuration config = new Configuration();
// TODO fix deprecation issues
config.locale = newLocale;
getResources().updateConfiguration(config, getResources().getDisplayMetrics());

And so I tried to use createConfigurationContext, with help from this answer, but that wasn't working either (and moreover was much more complex with several gotchas).

After extensive debugging, I noticed something:

MyAdapter adapter = new MyAdapter(getApplicationContext(), list);

On a hunch, I replaced getApplicationContext() with getContext(), and all of a sudden my list of items was using the proper language.

Turns out Oreo's getApplicationContext() no longer respects the custom locale you set. You must use the activity's context instead.

(Please note: I know I shouldn't have been using an app context for this, but this is a legacy app with many such issues. Fixing them is my ongoing daily struggle.)

Upvotes: 5

codespy
codespy

Reputation: 19

Please use activity.getResource() and use this Resource object. In my case this help.

Upvotes: -1

Related Questions