Save language chosen by user, Android

前端 未结 4 1851
醉话见心
醉话见心 2021-01-14 11:58

How can I change default string.xml? I can change my app to five different languages, but whenever I close the app and reopen it. It goes back to default English.

Is

4条回答
  •  失恋的感觉
    2021-01-14 12:04

    You can write to, then read from SharedPreferences to manage the user's chosen language

    To save:

    SharedPreferences shp = getSharedPreferences(
            "com.example.yourapp.PREFERENCES",Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = shp.edit();
    editor.putString("USER_LANGUAGE", language);
    editor.commit();
    

    To load:

    SharedPreferences shp = getSharedPreferences(
            "com.example.yourapp.PREFERENCES",Context.MODE_PRIVATE);
    String language = shp.getString("USER_LANGUAGE","en");
    

    When you load the language, modify the locale to use it

    Locale locale = new Locale(language);  
    Locale.setDefault(locale); 
    Configuration config = new Configuration(); 
    config.locale = locale; 
    getResources().updateConfiguration(config, getResources().getDisplayMetrics());
    

提交回复
热议问题