2016-07-26 124 views
0

我正在尝试制作一个示例应用程序,仅在语言环境更改上执行操作。我已经实施了ConfigurationChanged(...),并希望仅在Locale更改时将用户重定向到其他Activity。侦听Locale更改的Activity还侦听方向更改(我在清单中完成的)。Android - 区分配置更改

我的问题是,有没有什么办法来区分两种配置更改?

活性宣布在清单中,像这样:

<activity android:name=".views.MainActivity" 
       android:configChanges="layoutDirection|locale|orientation|screenSize"/> 

而且onConfigurationChange(..)方法是像这样:

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

     // should execute only on locale change 
     Intent intent = new Intent(this, SecondActivity.class); 
     startActivity(intent); 
    } 

回答

2

您可以节省您的区域在SharedPreferences和比较在onConfigurationChanged方法中,如果语言环境已更改。通过存储在的onCreate以前的语言环境的引用(第一次之前的任何区域转变活动负载发生)

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

不错,你能避免使用SharedPreferences,然后比较两个:

使用方法如下语言环境。 – user1841702

+0

当然,这使得它变得更加简单。没有想到,但我很高兴我可以帮助:) – babadaba