android语言环境会随机更改回默认设置

android语言环境会随机更改回默认设置,android,locale,Android,Locale,我有一个活动,在onCreate中,我从首选项加载语言并设置如下区域设置: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String lang = PreferenceManager.getDefaultSharedPreferences(this).getString("locale", "en"); Locale new

我有一个活动,在onCreate中,我从首选项加载语言并设置如下区域设置:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String lang = PreferenceManager.getDefaultSharedPreferences(this).getString("locale", "en");
    Locale newLocale = new Locale(lang);
    Locale.setDefault(newLocale);

    Configuration config = new Configuration();
    config.locale = newLocale;

    final Resources res = getResources();
    res.updateConfiguration(config, res.getDisplayMetrics());
}
我还覆盖OnConfiguration更改

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    String lang = PreferenceManager.getDefaultSharedPreferences(this).getString("locale", "en");
    Locale newLocale = new Locale(lang);
    Locale.setDefault(newLocale);

    Configuration config = new Configuration();
    config.locale = newLocale;

    final Resources res = getResources();
    res.updateConfiguration(config, res.getDisplayMetrics());
}
我在安卓2.3.7上有一个带有FragmentPagerAdapter和三个选项卡的ViewPager。问题是,有时在切换选项卡时,应用程序的区域设置会恢复为英语,因此从现在起,UI将使用混合语言。我总是在适配器的getItem()方法中为选项卡创建新片段。如果旋转设备,则区域设置再次正确

我还尝试将android:configChanges=“locale”放入清单中,而不是覆盖onConfigurationChanged(),但结果是一样的


最糟糕的是,它不是100%可复制的,它只发生过几次,我也收到了用户的报告。一旦应用程序启动,并且在切换几个选项卡后没有更改区域设置,那么它将正确运行,直到退出。

过了一段时间,我找到了一种方法。对我来说,唯一有效的解决方案是始终在main Acitivity的onCreate()中、在每个片段的onCreateView()中、在每个BroadcastReceiver()的onReceive()中(如果它加载了一些资源)以及在每个服务的开始处设置区域设置。为此,我在主活动(也是唯一的活动)中创建了一个静态方法setLocale()。如果您有更多的活动,可以将其放置在自定义应用程序类中

最后一件事。如果直接从IDE启动应用程序进行调试,有时甚至这种方法也不起作用。别担心,如果它在设备上正常运行,它会工作(至少对我来说)

public static void setLocale(Context context) {
    final String lang = PreferenceManager.getDefaultSharedPreferences(context).getString("locale", "en");
    final Locale newLocale = new Locale(lang);
    Locale.setDefault(newLocale);
    final Configuration config = new Configuration();
    config.locale = newLocale;

    final Resources res = context.getResources();
    res.updateConfiguration(config, res.getDisplayMetrics());
}

在这段时间之后,谷歌应该最终创建使用语言的正常方法,并给出示例。。