Change app language programmatically in Android

前端 未结 30 2960
面向向阳花
面向向阳花 2020-11-21 04:34

Is it possible to change the language of an app programmatically while still using Android resources?

If not, is it possible to request a resource in an specific lan

30条回答
  •  温柔的废话
    2020-11-21 05:18

    Here is some code that works for me:

    public class  MainActivity extends AppCompatActivity {
        public static String storeLang;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
    
            SharedPreferences shp = PreferenceManager.getDefaultSharedPreferences(this);
            storeLang = shp.getString(getString(R.string.key_lang), "");
    
            // Create a new Locale object
            Locale locale = new Locale(storeLang);
    
            // Create a new configuration object
            Configuration config = new Configuration();
            // Set the locale of the new configuration
            config.locale = locale;
            // Update the configuration of the Accplication context
            getResources().updateConfiguration(
                    config,
                    getResources().getDisplayMetrics()
            );
    
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    }
    

    Source: here

提交回复
热议问题