Change the language in the Android app
3 answers
You cannot translate the data returned by web services using Android, but you can change the language for rest as follows:
Try to re-create the activity after calling the method changeLocale
.
changeLocale("ar");
private void changeLocale(String lang) {
updateConfiguration(activity, lang); //lang = "en" OR "ar" etc
activity.recreate();
}
public static void updateConfiguration(Activity activity, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration configuration = new Configuration();
configuration.locale = locale;
Resources resources = activity.getBaseContext().getResources();
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
}
+3
source to share
Since Configuration.locale = locale has been deprecated in API> = 21, the following code can be used.
public void setLocale(Context context,String lang){
Locale[] locales = Locale.getAvailableLocales();
// print locales
boolean is_supported=false;
//check if the intended locale is supported by device or not..
for (int i = 0; i < locales.length; i++) {
if(lang.equals(locales[i].toString()))
{
is_supported=true;
break;
}
Log.e( "Languages",i+" :"+ locales[i]);
}
if(is_supported) {
Locale myLocale = new Locale(lang);
Resources res = context.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
conf.setLocale(myLocale);
} else {
conf.locale = myLocale;
}
res.updateConfiguration(conf, dm);
}else{
//do something like set english as default
}
Now use this function in your code by calling:
setLocale("hi");
You need to reload the activity screen by calling
Recreate ();
in your activities.
+2
source to share