Change the language in the Android app

We have the option to change the language by saving the strings files in the appropriate values ​​folder as mentioned below.

enter image description here

How can I translate the data I receive from web services? Is there a library available to accomplish this?

+3


source to share


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


You can use i18Next to translate the web service response



I18Next i18next = I18Next.getInstance();
Loader loader = i18next.loader();
loader.load();
loader.lang(String lang);

      

+2


source


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







All Articles