Внедряю в приложение функция смены языка через настройки. На API 26+ все работает без проблем, но если ниже 26 то реакции нет. Язык не меняется.
LocaleHelper.class
public class LocaleHelper {
private static final String SELECTED_LANGUAGE = "language";
public static Context onAttach(Context context) {
String lang = getLanguage(context);
return setLocale(context, lang);
}
public static String getLanguage(Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(SELECTED_LANGUAGE, Locale.getDefault().getLanguage());
}
public static Context setLocale(Context context, String language) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context, language);
}
return updateResourcesLegacy(context, language);
}
@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.setLocale(locale);
configuration.setLayoutDirection(locale);
return context.createConfigurationContext(configuration);
}
private static Context updateResourcesLegacy(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
configuration.setLayoutDirection(locale);
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
return context;
}
В MainActivity и MainApplication добавил:
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.onAttach(base));
}
Активити при выборе языка перезапускаю. После перезапуска функция updateResources из LocaleHelper выполняется. Видимо проблема именно в ней, но не могу понять почему. Рабочих примеров не нашол.
Подскажите пожалуйста в чем проблема.