Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change strings language in Android Activity

I'm doing an app with multilanguage. I understand the concept of string.xml for having the app language set to what is default for the phone. Is there some way of overriding this? For instance if I have a spanish phone I use in Spain but I still want to have the app in english ?

like image 425
Tomas F. Avatar asked Aug 27 '15 12:08

Tomas F.


1 Answers

You can change the language (locale) of your app programatically with a simple function. You only have to implement a method similar to the one you have below which receives a string as a parameter (like 'en' for English, 'es' for Spanish), where you can configure the locale for your app and refresh your current activity to reflect the changes. The locale you applied will not be changed until you manually change it again.

public void setLocale(String lang) { 
    myLocale = new Locale(lang); 
    Resources res = getResources(); 
    DisplayMetrics dm = res.getDisplayMetrics(); 
    Configuration conf = res.getConfiguration(); 
    conf.locale = myLocale; 
    res.updateConfiguration(conf, dm); 
    Intent refresh = new Intent(this, AndroidLocalize.class); 
    startActivity(refresh); 
    finish();
} 

Make sure you import the following packages:

import java.util.Locale; 
import android.os.Bundle; 
import android.app.Activity; 
import android.content.Intent; 
import android.util.DisplayMetrics; 
import android.content.res.Resources;
import android.content.res.Configuration;

Add also in manifest inside your activity tag android:configChanges="locale|orientation"

like image 152
arodriguezdonaire Avatar answered Oct 25 '22 16:10

arodriguezdonaire