我发现了只在Android N设备上才能复制的真正奇怪的错误。

在浏览我的应用程序时,可以更改语言。这是更改它的代码。

 public void update(Locale locale) {

    Locale.setDefault(locale);

    Configuration configuration = res.getConfiguration();

    if (BuildUtils.isAtLeast24Api()) {
        LocaleList localeList = new LocaleList(locale);

        LocaleList.setDefault(localeList);
        configuration.setLocales(localeList);
        configuration.setLocale(locale);

    } else if (BuildUtils.isAtLeast17Api()){
        configuration.setLocale(locale);

    } else {
        configuration.locale = locale;
    }

    res.updateConfiguration(configuration, res.getDisplayMetrics());
}


该代码在我的旅行活动中非常有用(通过recreate()调用),但是在接下来的所有活动中,所有String资源都是错误的。屏幕旋转将其修复。我该怎么办?我应该以其他方式更改Android N的语言环境还是仅仅是系统错误?

附言这是我发现的。第一次启动MainActivity时(在​​我的旅行之后)Locale.getDefault()是正确的,但是资源错误。但是在其他活动中,它会给我错误的语言环境和该语言环境的错误资源。旋转屏幕后(或可能进行其他一些配置更改),Locale.getDefault()是正确的。

最佳答案

好。最后,我设法找到了解决方案。

首先,您应该知道在25 API中已弃用Resources.updateConfiguration(...)。因此,您可以执行以下操作:

1)您需要创建自己的ContextWrapper,它将覆盖baseContext中的所有配置参数。例如,这是我的ContextWrapper,可以正确更改Locale。注意context.createConfigurationContext(configuration)方法。

public class ContextWrapper extends android.content.ContextWrapper {

    public ContextWrapper(Context base) {
        super(base);
    }

    public static ContextWrapper wrap(Context context, Locale newLocale) {
        Resources res = context.getResources();
        Configuration configuration = res.getConfiguration();

        if (BuildUtils.isAtLeast24Api()) {
            configuration.setLocale(newLocale);

            LocaleList localeList = new LocaleList(newLocale);
            LocaleList.setDefault(localeList);
            configuration.setLocales(localeList);

            context = context.createConfigurationContext(configuration);

        } else if (BuildUtils.isAtLeast17Api()) {
            configuration.setLocale(newLocale);
            context = context.createConfigurationContext(configuration);

        } else {
            configuration.locale = newLocale;
            res.updateConfiguration(configuration, res.getDisplayMetrics());
        }

        return new ContextWrapper(context);
    }
}


2)这是您在BaseActivity中应该做的事情:

@Override
protected void attachBaseContext(Context newBase) {

    Locale newLocale;
    // .. create or get your new Locale object here.

    Context context = ContextWrapper.wrap(newBase, newLocale);
    super.attachBaseContext(context);
}


注意:


  如果要在以下位置更改语言环境,请记住要重新创建活动
  您的应用程序在某处。您可以覆盖要使用的任何配置
  这个解决方案。

10-08 07:10
查看更多