Android - 区分配置更改

时间:2016-07-26 10:48:57

标签: android android-configchanges

我正在尝试创建一个仅针对区域设置更改执行操作的示例应用。我已经实现了onConfigurationChanged(...),并希望仅在Locale更改时将用户重定向到另一个Activity。侦听区域设置更改的活动还会侦听方向更改(我已在清单中执行此操作)。

我的问题是,有没有办法区分这两种配置变化?

活动在清单中声明如下:

Integer i = Optional.ofNullable(str).map(Integer::parseInt).orElse(null);

onConfigurationChange(..)方法是这样的:

Date date = Optional.ofNullable(str).filter(MyDateUtils::isValidDate).map(MyDateUtils::toDate).orElse(null);

1 个答案:

答案 0 :(得分:2)

如果语言环境已更改,您可以在SharedPreferences中保存语言环境并在onConfigurationChanged方法中进行比较。

像这样使用:

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

    SharedPreferences prefs = getSharedPreferences(
  "yourapp", Context.MODE_PRIVATE);
    prefs.getString("locale", "DEFAULT"); 

    //newConfig.locale is deprecated since API lvl 24, you can also use newConfig.getLocales().get(0) 
    if(!locale.equalsIgnoreCase(newConfig.locale.toLanguageTag()) {
        // should execute only on locale change
        SharedPreferences settings = getSharedPreferences("yourapp", MODE_PRIVATE);
        SharedPreferences.Editor prefEditor = settings.edit();
        prefEditor.putString("locale", newConfig.locale.toLanguageTag());
        prefEditor.commit();
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);  
    }
}