Смена языка вручную не работает на устройствах Samsung - PullRequest
0 голосов
/ 08 марта 2020

У меня проблемы с изменением языка приложения вручную, в приложении я предлагаю пользователям возможность изменить язык приложения на свой предпочтительный, приведенный ниже код отлично работает даже в Android ( Pixel 3 Emulator ), но по какой-то причине он работает не на всех устройствах Samsung

            Context context = LocaleUtils.setLocale(getApplicationContext(), languageCode);
            Resources resources = context.getResources();
            Locale myLocale = new Locale(languageCode);
            DisplayMetrics dm = resources.getDisplayMetrics();
            Configuration conf = resources.getConfiguration();
            conf.locale = myLocale;
            resources.updateConfiguration(conf, dm);
            Intent intent = getBaseContext().getPackageManager().getLaunchIntentForPackage(
                    getBaseContext().getPackageName());
            if (intent != null) {
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            }

Класс приложения:

 @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        LocaleUtils.onAttach(base, Locale.getDefault().getLanguage());
        MultiDex.install(this);
   }

на каждом Активность :

  @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(ViewPumpContextWrapper.wrap(LocaleUtils.onAttach(newBase)));
    }

1 Ответ

0 голосов
/ 09 марта 2020

Я боролся с динамическими c Изменение языка на устройствах Samsung даже до Android 10.
Возможно, сейчас есть лучшее решение,
, но в то же время в дополнение к тому, что вы сделали,
Я закончил тем, что получил все строки по идентификаторам ресурсов следующим образом:

public static String getStringByIdentifier(final Context context, final String stringResIdName, final boolean forceRefresh) {
        final Resources res = getResources(context, forceRefresh);
        String result;
        try {
            result = res.getString(res.getIdentifier(stringResIdName, "string",
                    context.getPackageName()));
        } catch (final Resources.NotFoundException e) {
            result = stringResIdName; // TODO or here you may throw an Exception and handle it accordingly. 
        }
        return result;
    }

public static String getStringByIdentifier(final Context context, final String stringResIdName) {
        return getStringByIdentifier(context, stringResIdName, false);
    }

 private static Resources getResources(final Context context, final boolean refreshLocale) {
        if (!refreshLocale) {
            return context.getResources();
        } else {
            final Configuration configuration = new Configuration(context.getResources().getConfiguration());
            configuration.setLocale(Locale.getDefault());
            return context.createConfigurationContext(configuration).getResources();
        }
    }

Таким образом, вы должны установить текст следующим образом:

textView.setText(AndroidUtils.getStringByIdentifier(context, "string_res_name"));

Где соответствующая строка Ресурс:

<string name="string_res_name">Some string</string>
...