We have option to change language by keeping string files in appropriate values folder as mention in below image.
How can I translate the data which I am getting from Web services? Is there any library available to achieve this?
You can not translate data returned by web services using android but can change language for rest the app as mentioned below:
Try re-creating activity after calling changeLocale method.
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());
}
As Configuration.locale = locale is 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 your activity screen by calling
recreate();
in your activity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With