I have created a bilingual (having two languages) android application. I have inserted my resource strings in two files:
For Persian language (default)
values/strings_locale.xml
For English language
values-en/strings_locale.xml
I my first launching Activity I have inserted the following code:
Configuration c = new Configuration(this.getResources().getConfiguration());
c.locale = new Locale("fa_IR");
this.getResources().updateConfiguration(c, this.getResources().getDisplayMetrics());
So after this code, my default language will be Persian and all of strings in all of Activities are shown in Persian language correctly.
But the problem is when the screen of the device is rotated, all of the strings are shown in English and it also happens for all other Activities! And I have to close and reopen my application.
Why this happens and how I can solve this problem?
Some device configurations can change during runtime (such as screen orientation, keyboard availability, and when the user enables multi-window mode). When such a change occurs, Android restarts the running Activity ( onDestroy() is called, followed by onCreate() ).
So instead of destroying and recreating your Activity, Android will just rotate the screen and call one of the lifecycle methods: onConfigurationChanged. If you have a Fragment attached to this Activity, it will also receive a call to its onConfigurationChanged method.
You can make class which extends Application
. There you can override one method which gets called everytime you change configuration (example when screen orientation gets changed).
Something like:
public class MyApplication extends Application {
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setLocale();
}
private void setLocale() {
Locale locale = new Locale("fa_IR");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
}
}
And dont forget to declare it in the manifest: example of Application class
In AndroidManifest.xml:
<application
android:name="com.blaablaa.bumbam.MyApplication"
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With