How to change language of an application from app setting?
I want my app to support three languages: Spanish, Portuguese and English and give an option to select the language from the settings menu of my app.
How to change language of an application from app setting?
I want my app to support three languages: Spanish, Portuguese and English and give an option to select the language from the settings menu of my app.
Using following class you can change language from application.
public class LocaleHelper {
private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";
public static void onCreate(Context context) {
String lang = getPersistedData(context, Locale.getDefault().getLanguage());
setLocale(context, lang);
}
public static void onCreate(Context context, String defaultLanguage) {
String lang = getPersistedData(context, defaultLanguage);
setLocale(context, lang);
}
public static String getLanguage(Context context) {
return getPersistedData(context, Locale.getDefault().getLanguage());
}
public static void setLocale(Context context, String language) {
persist(context, language);
updateResources(context, language);
}
private static String getPersistedData(Context context, String defaultLanguage) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
}
private static void persist(Context context, String language) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SELECTED_LANGUAGE, language);
editor.apply();
}
private static void updateResources(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Resources resources = context.getResources();
android.content.res.Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
DisplayMetrics dm = resources.getDisplayMetrics();
resources.updateConfiguration(configuration, dm);
}
}
call language change using following object.
LocaleHelper.setLocale(getBaseContext(), "ar");
Please do not forgot to refresh current activity after call this. Hope this will help you.
Implementing Localization is your solution
Create seperate values folder for each language and android os will automatically select corresponding values based on locale on ur device
Please follow steps here
http://www.compiletimeerror.com/2014/10/android-localization-tutorial-with.html?m=1
https://www.tutorialspoint.com/android/android_localization.htm