While developing your awesome application, sometimes you are required to add a feature to change the language of your app on the fly. However, Android OS does not directly support this behaviour. And therefore, you need to solve this situation in some other ways.
Android by default uses the locale of the device to select the appropriate language
dependent resources. And most of the time this behaviour is enough for common applications.
// set language prefix in shared preference
Android by default uses the locale of the device to select the appropriate language
dependent resources. And most of the time this behaviour is enough for common applications.
There are some difficulties which you have to overcome to change the language programmatically.
- Your application will not remember your language change after it is closed or recreated during the configuration change.
- You should update currently visible UI properly according to the selected language.
// set language prefix in shared preference
LANGUAGE_TYPE = "en" || "hi" || "gu" etc..
Utils.setStringPreference(activity, AppConstants.PREF_APP_LANGUAGE, LANGUAGE_TYPE);// get language prefix from shared preference and set to Locale of Android System
public void setLanguage() { String defaultLANG = Locale.getDefault().getLanguage(); String languageToLoad = "en"; // your language switch (Utils.getStringPreference(MainActivity.this, AppConstants.PREF_APP_LANGUAGE, "0")) { case "0": languageToLoad = "en"; break; case "1": languageToLoad = "hi"; break; case "2": languageToLoad = "gu"; break; } Locale locale = new Locale(languageToLoad); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); }