Viktor
Viktor

Reputation: 326

Change default Locale language android

I have made 2 different strings.xml, 1 for swedish and 1 for english.

Code for changing Locale

 public void setLocale(String lang) {
    Locale myLocale = new Locale(lang);
    Resources res = getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = myLocale;
    res.updateConfiguration(conf, dm);
    Intent refresh = new Intent(getContext(), BaseActivity.class);
    startActivity(refresh);
}

Onclicklisteners for switching language

swedish.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setLocale("sv");
        }
    });
    english.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setLocale("en");
        }
    });

The thing is, the app took it by itself to start the app on swedish, which, as far as I know, haven't set by myself. How do I change the default Locale when the app starts?

Question

  1. How do I set the app to start with using the english xml?
  2. Does anyone have a tip on how to store the choice the user makes? I want it to store if the user presses to use swedish if it closes the app.

Upvotes: 1

Views: 4320

Answers (3)

Farshid Ahmadi
Farshid Ahmadi

Reputation: 513

It's just for some languages.

I found when I use translator editor of android studio, to add a locale for example Persian(fa), instead of values-fa android studio add values-fa-rIRso when we asked for Locale("fa") it won't works. So if it doesn't work go to project view and rename your folder (for my example res/values-fa-rIR to res/values-fa).

And setContentView() after that,also

Good luck

Upvotes: 3

Naimatullah
Naimatullah

Reputation: 4079

public void changeLanguage(){ try {

        Resources res = mContext.getResources();
        // Change locale settings in the app.
        DisplayMetrics dm = res.getDisplayMetrics();
        android.content.res.Configuration conf = res.getConfiguration();
        conf.locale = new Locale("en");
        // conf.locale = new Locale("en");
        res.updateConfiguration(conf, dm);
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
}

Upvotes: 0

shahid17june
shahid17june

Reputation: 1577

When user press on language selection store this value into prefrence and once you back again then you have already a stored value in prefrence. now just call the method like:- setLocale_forstartup("en");

`public void setLocale_forstartup(String lang) {

        myLocale = new Locale(lang);
        Locale.setDefault(myLocale);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);

    }`

Upvotes: 0

Related Questions