简体   繁体   中英

How do I save user's locale settings (in app)?

I'm making an app that has two available languages. User is changing between languages with a button click. Here are my onClick methods:

public void setLocaleEng(View v){
    Locale localeEng = new Locale("en");
    Locale.setDefault(localeEng);
    Configuration configEng = new Configuration();
    configEng.locale = localeEng;
    getBaseContext().getResources().updateConfiguration(configEng, getBaseContext().getResources().getDisplayMetrics());
    Intent intent = new Intent(NastavitveJezika.this, MainActivity.class);
    finish();
    startActivity(intent);
}

public void setLocaleSlo(View v){
    Locale localeSlo = new Locale("sl");
    Locale.setDefault(localeSlo);
    Configuration configSlo = new Configuration();
    configSlo.locale = localeSlo;
    getBaseContext().getResources().updateConfiguration(configSlo, getBaseContext().getResources().getDisplayMetrics());
    Intent intent = new Intent(NastavitveJezika.this, MainActivity.class);
    finish();
    startActivity(intent);
}

This works as it should, but when user completely exits application and re-opens it, it will be back to default (english). How do I make my app remember which language settings the user has chosen? If the answer is Shared Preferences, then how? I've only used shared preferences to store strings and booleans so far, I don't know how I would approach something like this.

If the answer is Shared Preferences, then how? I've only used shared preferences to store strings.

Yes, answer is SharedPreferences and you can use it to store Strings, just like you did before. Just make it store "en" or "sl" and then

    String enOrSlReadFromSharedPrefs = readSharedPrefsJustLikeYouDidBefore();
    Locale locale = new Locale(enOrSlReadFromSharedPrefs);
    Locale.setDefault(locale);
    Configuration configSlo = new Configuration();
    configSlo.locale = localeSlo;
    getBaseContext().getResources().updateConfiguration(configSlo, getBaseContext().getResources().getDisplayMetrics());
    Intent intent = new Intent(NastavitveJezika.this, MainActivity.class);
    finish();
    startActivity(intent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM