0

I have problem to change language when my device language not be English (For example Portuguese). This is my code:

  Locale locale = new Locale("en");
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        context.getResources().updateConfiguration(config,
                context.getResources().getDisplayMetrics());

I check some other asnwers like this but it's not working too

SharedPrefUtils.saveLocale(locale); // optional - Helper method to save the selected language to SharedPreferences in case you might need to attach to activity context (you will need to code this)
Resources resources = getResources();
Configuration configuration = resources.getConfiguration();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
    configuration.setLocale(locale);
} else{
    configuration.locale=locale;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
    getApplicationContext().createConfigurationContext(configuration);
} else {
    resources.updateConfiguration(configuration,displayMetrics);
}

So what's my problem?

3 Answers3

0

You might need to recreate activity after change default locale.

getActivity().recreate();
Ferhat Ergün
  • 135
  • 1
  • 10
0

You need to pass in the new configuration context to ContextWrapper Superclass.

Override attachBaseContext in your activity and pass the new context as -

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(updatedConfigurationContext(base));
}

And return new context from getApplicationContext().createConfigurationContext(configuration);

as you are doing above.

Vishal Arora
  • 2,524
  • 2
  • 11
  • 14
0

No idea where you wanna do this, so I just assume it's in an Activity. Also this answer is in Kotlin, if you want it in Java check the following post: How to convert a kotlin source file to a java source file

Activity:

override fun attachBaseContext(ctx: Context?) {
    super.attachBaseContext(ContextWrapper.wrap(ctx, yourLocale))
}

ContextWrapper:

class ContextWrapper(context: Context?) : android.content.ContextWrapper(context) {
    companion object {
        fun wrap(context: Context?, locale: Locale): ContextWrapper {
            val configuration = context?.resources?.configuration
            configuration?.setLocale(locale)

            if (Build.VERSION.SDK_INT >= 24) {
                val localeList = LocaleList(locale)
                LocaleList.setDefault(localeList)
                configuration?.locales = localeList
            }

            val ctx = if(configuration != null) context.createConfigurationContext(configuration) else null
            return ContextWrapper(ctx)
        }
    }
}

Recreate you Context (Activity):

Use recreate() in your Activity to restart your Activity context.

Javatar
  • 2,518
  • 1
  • 31
  • 43