Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to change language in Oreo

I'm trying to use Arabic and English in my app. Its working fine on devices running on android Nougat or below. But it's not working on oreo devices. Is there some new code requirement in API 26? I am using the code below.

public void changeLanguage(Context context, String language) {
    Locale locale = new Locale(language);
    Locale.setDefault(locale);
    Configuration config = context.getResources().getConfiguration();
    config.setLocale(locale);
    context.createConfigurationContext(config);
    context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
}

and I'm passing "en" and "ar" as language argument.

like image 382
AFLAH ALI Avatar asked Dec 26 '17 11:12

AFLAH ALI


3 Answers

When you set new Locale you should restart your Activity. You can perform it using the next snippet of code:

private void restartActivity() {
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}

Then your changeLanguage() method will look in a next way:

public void changeLanguage(Context context, String language) {
    Locale locale = new Locale(language);
    Locale.setDefault(locale);
    Configuration config = context.getResources().getConfiguration();
    config.setLocale(locale);
    context.createConfigurationContext(config);
    context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());

    restartActivity();
}
like image 129
Alexey Denysenko Avatar answered Nov 03 '22 02:11

Alexey Denysenko


I recently faced issue related to layout direction on Oreo. Resources were being updated but Layout direction not changing.

Below code worked for me.

 public static void setRTLSupportIfRequired(AppCompatActivity activity) {
        if(getLanguageFromPrefs(activity).equals("ar")) {
            activity.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
        }else{
            activity.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
        }

    }

Note: Previously I were using View.LAYOUT_DIRECTION_LOCALE but it was not working on Oreo

like image 22
Zaid Mirza Avatar answered Nov 03 '22 00:11

Zaid Mirza


Locale locale = new Locale(lang);
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        config.setLocale(locale);
    } else {
        config.locale = locale;
    }
    context.getApplicationContext().getResources().updateConfiguration(config,
            context.getApplicationContext().getResources().getDisplayMetrics());

This worked for me.

like image 41
husen Avatar answered Nov 03 '22 00:11

husen