手动更改语言无法在Samsung设备上使用

问题描述 投票:0回答:1

我在手动更改应用程序语言时遇到麻烦,在应用程序中,我为用户提供了将应用程序语言更改为他们喜欢的语言的能力,即使在Android中,以下代码也可以正常工作(Pixel 3 Emulator ),但由于某些原因,它不适用于所有三星设备

            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)));
    }
java android locale android-10.0
1个回答
0
投票

甚至在Android 10之前,我都在为动态调整Locale设备的语言环境而努力。现在可能有更好的解决方案,但是当时除了您所做的之外,我最终以以下方式通过资源标识符检索了所有字符串:

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>
© www.soinside.com 2019 - 2024. All rights reserved.