My app supports 3 (soon 4) languages. Since several locales are quite similar I'd like to give the user the option to change locale in my application, for instance an Italian person might prefer Spanish over English.
Is there a way for the user to select among the locales that are available for the application and then change what locale is used? I don't see it as a problem to set locale for each Activity since it is a simple task to perform in a base class.
EDIT 21st OCTOBER 2022
Starting from Android 13 you can now set your locale from the
AppCompatDelegate
with the methodsetApplicationLocales(appLocale)
and it has backwards compatibility.For API 33 and above:
The process is quite simple and you can achieve it as follow:
While using this you should no longer need to call
recreate()
on the activity as the docs mention:API lower than 33
If you are targetting an API lower than 33 you will need to also add a service to your manifest in order to handle locale storage:
This is only available for AndroidX from androidx.appcompat:appcompat:1.6.0-alpha01
You can find the documentation here
-------------- Old Answers ------------
For people still looking for this answer, since
configuration.locale
was deprecated from API 24, you can now use:Take in consideration that the minSkdVersion for this method is API 17.
Full example code:
Don't forget that, if you change the locale with a running Activity, you will need to restart it for the changes to take effect.
EDIT 11th MAY 2018
As from @CookieMonster's post, you might have problems keeping the locale change in higher API versions. If so, add the following code to your Base Activity (BaseActivity extends AppCompatActivity / other activities) so that you update the context locale on every Activity creation:
If you use this, don't forget to save the language to SharedPreferences when you set the locale with
setLocale(locale)
EDIT 7th APRIL 2020
You might be experiencing issues in Android 6 and 7, and this happens due to an issue in the androidx libraries while handling the night mode. For this you will also need to override
applyOverrideConfiguration
in your base activity and update the configuration's locale in case a fresh new locale one is created.Sample code: