Java Android显示文本语言在某些部分出错

Java Android显示文本语言在某些部分出错,java,android,Java,Android,在应用程序上,有时会显示错误的文本语言,例如更改应用程序语言时,一个活动会同时显示“zh_tw”和“en”。但有时它没有问题 以下是更改语言代码: public static void setApplicationLanguage(Context context, Locale locale) { Resources resources = context.getApplicationContext().getResources(); DisplayMetrics dm = r

在应用程序上,有时会显示错误的文本语言,例如更改应用程序语言时,一个活动会同时显示“zh_tw”和“en”。但有时它没有问题

以下是更改语言代码:

public static void setApplicationLanguage(Context context, Locale locale) {

    Resources resources = context.getApplicationContext().getResources();
    DisplayMetrics dm = resources.getDisplayMetrics();
    Configuration config = resources.getConfiguration();
    config.locale = locale;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context.getApplicationContext().createConfigurationContext(config);
        Locale.setDefault(locale);
    }
    resources.updateConfiguration(config, dm);

    Intent intent = new Intent(context, HomeActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    finishAffinity();
    context.startActivity(intent);
}

我谷歌搜索无法找到任何解决方案或类似的情况。谢谢。

为此,请从扩展应用程序类的类(基类)调用LocaleeManager类中的函数 在你的申请课上

  @Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(LocaleManager.setLocale(base));
}
在您的区域设置管理器中。此代码在本地应用程序的API更改方面应该没有问题。它对我有用

private static Context updateResources(Context context, String language) {
    Locale locale = new Locale(language);
    Locale.setDefault(locale);
    Resources res = context.getResources();
    Configuration config = new Configuration(res.getConfiguration());
    config.setLocale(locale);
    context = context.createConfigurationContext(config);
    return context;
}

谢谢你的帮助。我会尝试你的建议。我已经尝试了你的代码,但没有工作。你有其他的想法和建议吗?感谢太晚了。您使用的是应用程序上下文还是活动?如果您正在使用应用程序上下文,则必须重新启动整个应用程序。如果您使用的是活动上下文,而您的应用程序由多个活动组成,则应将其更改为应用程序上下文并重新启动整个应用程序。如果您使用的是单个活动,那么活动上下文应该可以工作。感谢您的回复。上下文来自活动和多个活动。我将尝试从application.ok更改上下文。另外,请将Appcompat更新至最新版本。我想我忘了在之前的回答中解释上下文。如果您使用应用程序上下文获取资源,但在更改语言后只重新启动活动,则只有布局文件中的字符串才会被翻译。因为应用程序从未重新启动,并且应用程序上下文相同,所以资源不会得到更新。