android locale随机更改回默认值

时间:2012-04-13 10:21:48

标签: android locale

我有一个活动,在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());
}

我也覆盖onConfigurationChanged

@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());
}

我有一个带有FragmentPagerAdapter的ViewPager和android 2.3.7上的三个标签。问题是,有时在切换选项卡时,应用程序的语言环境会恢复为英语,因此UI从现在开始混合语言。我总是为适配器的getItem()方法中的选项卡创建新的片段。如果我旋转设备,区域设置再次正确。

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

最糟糕的是,它不是100%可重复的,它只发生了一些时间,我也有用户的报告。一旦应用程序启动并且在切换几个选项卡后它没有更改语言环境,那么它将正确直到退出。

1 个答案:

答案 0 :(得分:13)

过了一段时间,我想出了办法。对我有用的唯一解决方案是始终在主要Acitivity的onCreate(),每个Fragment的onCreateView(),每个BroadcastReceiver()的onReceive()(如果它加载某些资源)和每个Service的开头设置语言环境。为此我在main和only活动中创建了一个静态方法setLocale()。如果您有更多活动,可以将其放在自定义Application类中。

最后一件事。如果应用程序直接从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());
}