Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change language throughout android application

We have option to change language by keeping string files in appropriate values folder as mention in below image.

enter image description here

How can I translate the data which I am getting from Web services? Is there any library available to achieve this?

like image 873
selva_pollachi Avatar asked Dec 06 '25 15:12

selva_pollachi


2 Answers

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());
}
like image 57
PEHLAJ Avatar answered Dec 09 '25 20:12

PEHLAJ


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.

like image 32
Alvi Avatar answered Dec 09 '25 20:12

Alvi