In my Android app i want to change the default language dinamically. I have implemented this method:
public void changeLanguage(String lang) { //lang="it" or "en" for example
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
@Override
public void run()
{
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
{
finish();
startActivity(getIntent());
} else recreate();
}
}, 1);
}
and in the manifest i added to my MainActivity this line:
android:configChanges="locale|orientation"
i also tried this:
android:configChanges="locale|layoutDirection"
This solution works well, but as soon as the screen is rotated comes back to the default configuration and the language is restored.
How can i resolve this issue?
You could save your language configuration in the callback onSaveInstanceState
, when the system re-create your activity because of rotation, reload the saved locale values.
private static final String LANG = "lang";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
Configuration configuration = getResources().getConfiguration();
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
configuration.locale = new Locale(savedInstanceState.getString(LANG));
getResources().updateConfiguration(configuration, displayMetrics);
}
}
/*
* (non-Javadoc)
*
* @see
* android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os
* .Bundle)
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
outState.putString(LANG, "it");
}