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.
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();
}
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With