Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Language switching inside app android

How do I implement language switching without having to manually set locale inside an Android app? I know the app will load the strings.xml according to locale during startup, but I don't want this choice to be made based on system locale, but instead to be user-specified in Settings.

Or, is manually setting locale fine?

like image 764
Sergo Pasoevi Avatar asked Sep 24 '13 13:09

Sergo Pasoevi


1 Answers

You can extend Application class (you have to declare it in the manifest as well) and put something like this in it.

Whenever you want to change language you can then call

((App)getApplicationContext()).changeLang(lang);

from within your activity. R.string.locale_lang is just a key which is stored in strings.xml for shared preferences

public class App extends Application {

    private Locale locale = null;

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (locale != null) {
            Locale.setDefault(locale);
            Configuration config = new Configuration(newConfig);
            config.locale = locale;
            getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
        String lang = settings.getString(getString(R.string.locale_lang), "");
        changeLang(lang); 
    }

    public void changeLang(String lang) {
        Configuration config = getBaseContext().getResources().getConfiguration();
        if (!"".equals(lang) && !config.locale.getLanguage().equals(lang)) {

            Editor ed = PreferenceManager.getDefaultSharedPreferences(this).edit();
            ed.putString(getString(R.string.locale_lang), lang);
            ed.commit();

            locale = new Locale(lang);
            Locale.setDefault(locale);
            Configuration conf = new Configuration(config);
            conf.locale = locale;
            getBaseContext().getResources().updateConfiguration(conf, getBaseContext().getResources().getDisplayMetrics());
        }
    }

    public String getLang(){
        return PreferenceManager.getDefaultSharedPreferences(this).getString(this.getString(R.string.locale_lang), "");
    }



}
like image 163
kjurkovic Avatar answered Oct 03 '22 13:10

kjurkovic