Save language when the screen is rotated

This question already has an answer here:

  • Saving Android Activity state using Save Instance State 25 answers

  • Using shared preferences you can store the lanuage and get the stored value on screen orientation change.

    public String 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(this, Login.class);
        startActivity(refresh);
        finish();
        // save shared preference here or later, your choice.
        return lang;
    }
    

    Code to create and save shared preference.

    SharedPreferences  preferences = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor nameEditor = preferences.edit();
    nameEditor.putString("saved_lang", lang);
    nameEditor.commit();
    

    Code to retrieve value of shared preference.

    //To get language when screen changes.
    String lang = preferences.getString("saved_lang", "");
    

    You can use the same principal to save other values and settings.

    链接地址: http://www.djcxy.com/p/26196.html

    上一篇: 在Android中保存和存储活动

    下一篇: 屏幕旋转时保存语言