0

I am adding a new feature to an android application, that enables the users to switch between two languages.

So far to test out the change of Locale I have been using the following piece of code in one of my Activities.

    Locale myLocale = new Locale("ru");
    Locale.setDefault(myLocale);

    Resources res = this.getResources();

    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();

    Locale current = getResources().getConfiguration().locale;

    if (current.getLanguage().equals(myLocale.getLanguage())){

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {

            conf.setLocale(myLocale);
            createConfigurationContext(conf);
            recreate();

        }else{

            conf.locale = myLocale;
            res.updateConfiguration(conf, res.getDisplayMetrics());
            recreate();

        }

    }

    setContentView(R.layout.activity_main);

The reason for checking the Version Code is that createConfigurationContext() requires API Level 17 and I'm using API Level 16. So this conditional lets me use the deprecated updateConfiguration() and also the createConfigurationContext().

I have also created the strings.xml for the relevant language and added a few values for testing.

File Structure

What has been achieved so far is that the Dates are being shown in the translated language, so that tells me that the Locale has actually been changed to the correct one. Other strings that are supposedly taken from strings.xml (ru) aren't changing at all.

Are strings with multiple translations called in a different way from the layout xmls (See code below)? or maybe my structure isn't right?

android:text="@string/upcoming_title"
Steve Cortis
  • 522
  • 1
  • 6
  • 25
  • are you changing the locale before or after inflating your layouts? It will not magically update your inflated views. Only strings loaded _after_ the change will be affected, and usually an activity restart is required – David Medenjak Apr 28 '17 at 07:29
  • Yes it is, and also the activity is being restarted by the recreate() method and can confirm that is happening through the Logs. – Steve Cortis Apr 28 '17 at 07:33

1 Answers1

0

After posting the question I kept trying some stuff, and decided to try to add the following answer from another post:

https://stackoverflow.com/a/40704077/2199589

This worked as expected.

Community
  • 1
  • 1
Steve Cortis
  • 522
  • 1
  • 6
  • 25