Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After the screen rotation, the language of my application will be changed

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?

like image 591
Bobs Avatar asked Nov 04 '13 10:11

Bobs


People also ask

What happens when screen orientation changes in Android?

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() ).

Which method is called when screen changes orientation?

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.


1 Answers

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"
    ...
like image 181
vilpe89 Avatar answered Oct 02 '22 06:10

vilpe89