Multiple language application
Multiple language application
This below code is use to change application language.
Set strings in string.xml file
<string name="english">en</string>
<string name="arabic">ar</string>
Add method in Utils.java class
/**
* Change language
* @param context
* @param locale for ex. "en", "ar"
*/
public static void forcefullyLocaleChange(Context context, String locale) {
Locale.setDefault(new Locale(locale));
Resources res = context.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
conf.setLocale(new Locale(locale));
} else {
conf.locale = new Locale(locale);
}
res.updateConfiguration(conf, dm);
Log.d("LANGUAGE", getCurrentLanguage());
}
Add this code in your activity file
/**
* By selecting language call this method and pass selected language
* @param language for ex. "en", "ar"
**/
private void changeLanguage(String language) {
// get last selected language
String lastLanguage = SharedPrefUtils.getPreference(context, getString(R.string.pref_locale), "");
// check last language is not null and not same as selected language
if (lastLanguage != null && !TextUtils.equals(lastLanguage, language)) {
// set language in localisation
Utils.forcefullyLocaleChange(context, language);
// save language into shared preference file
SharedPrefUtils.setPreference(context, getString(R.string.pref_locale), language);
// start self activity to display language change
restartActivity();
}
}
private void restartActivity() {
Intent intent = getIntent();
supportFinishAfterTransition();
startActivity(intent);
}
Comments
Post a Comment