Is it possible, at runtime, to know which resources languages are embedded in my app?
i.e the presence of this folders:
values-en
values-de
values-fr
...
It's complicated because even if you have a folder named values-de it doesn't mean you have any resources there. If you have string.xml in values-de it doesn't mean you have string value there.
values:
<resources>
<string name="app_name">LocTest</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
</resources>
values-de:
<resources>
<string name="hello_world">Hallo Welt!</string>
</resources>
You can test if a resource for a specific locale is different than the default:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
Resources r = getResources();
Configuration c = r.getConfiguration();
String[] loc = r.getAssets().getLocales();
for (int i = 0; i < loc.length; i++) {
Log.d("LOCALE", i + ": " + loc[i]);
c.locale = new Locale(loc[i]);
Resources res = new Resources(getAssets(), metrics, c);
String s1 = res.getString(R.string.hello_world);
c.locale = new Locale("");
Resources res2 = new Resources(getAssets(), metrics, c);
String s2 = res2.getString(R.string.hello_world);
if(!s1.equals(s2)){
Log.d("DIFFERENT LOCALE", i + ": "+ s1+" "+s2 +" "+ loc[i]);
}
}
It has one fault - you can check one value whether it has translation.
The dirty code above will print something like:
LOCALE(5667): 51: en_NZ LOCALE(5667): 52: uk_UA LOCALE(5667): 53:
nl_BE LOCALE(5667): 54: de_DE DIFFERENT LOCALE(5667): 54: Hallo Welt!
Hello world! de_DE LOCALE(5667): 55: ka_GE LOCALE(5667): 56: sv_SE
LOCALE(5667): 57: bg_BG LOCALE(5667): 58: de_CH DIFFERENT
LOCALE(5667): 58: Hallo Welt! Hello world! de_CH LOCALE(5667): 59:
fr_CH LOCALE(5667): 60: fi_FI
AssetManager.getLocales() is actually the way to do this. However, from the public API every AssetManager you create also has the framework resources included in its search path... so when you call AssetManager.getLocales() you will also see any locales that are part of the framework resources. There is no way to get around this with the SDK, sorry.
For anyone using Gradle, I did it like so below it traverses all strings.xml, grabs the directory names and figures out the locales from there. It adds a String[] to BuildConfig which you can access as BuildConfig.TRANSLATION_ARRAY
task buildTranslationArray << {
def foundLocales = new StringBuilder()
foundLocales.append("new String[]{")
fileTree("src/main/res").visit { FileVisitDetails details ->
if(details.file.path.endsWith("strings.xml")){
def languageCode = details.file.parent.tokenize('/').last().replaceAll('values-','').replaceAll('-r','-')
languageCode = (languageCode == "values") ? "en" : languageCode;
foundLocales.append("\"").append(languageCode).append("\"").append(",")
}
}
foundLocales.append("}")
//Don't forget to remove the trailing comma
def foundLocalesString = foundLocales.toString().replaceAll(',}','}')
android.defaultConfig.buildConfigField "String[]", "TRANSLATION_ARRAY", foundLocalesString
}
preBuild.dependsOn buildTranslationArray
So after the above task occurs (on prebuild) the BuildConfig.TRANSLATION_ARRAY has your list of locales.
I'm not a Gradle/Groovy expert so this could definitely be a bit neater.
Reasoning - I ran into too many issues implementing pawelzieba's solution, I had no reliable strings to 'compare' as the translations were crowdsourced. The easiest way then was to actually look at the values-blah folders available.
Inspired by Mendhak's solution I created something a bit cleaner:
defaultConfig {
....
def locales = ["en", "it", "pl", "fr", "es", "de", "ru"]
buildConfigField "String[]", "TRANSLATION_ARRAY", "new String[]{\""+locales.join("\",\"")+"\"}"
resConfigs locales
}
Then in Java use:
BuildConfig.TRANSLATION_ARRAY
Advatages of this method:
Smaller apk - resConfigs will cut out resources from libraries which you don't need (some have hundreds)
Fast - No need to parse resource configurations
Inspired by the answers above I created a simple method to get all app's languages based on provided translations:
public static Set<String> getAppLanguages( Context ctx, int id ) {
DisplayMetrics dm = ctx.getResources().getDisplayMetrics();
Configuration conf = ctx.getResources().getConfiguration();
Locale originalLocale = conf.locale;
conf.locale = Locale.ENGLISH;
final String reference = new Resources( ctx.getAssets(), dm, conf ).getString( id );
Set<String> result = new HashSet<>();
result.add( Locale.ENGLISH.getLanguage() );
for( String loc : ctx.getAssets().getLocales() ){
if( loc.isEmpty() ) continue;
Locale l = Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT_WATCH ? new Locale( loc.substring( 0, 2 ) ) : Locale.forLanguageTag( loc );
conf.locale = l;
if( !reference.equals( new Resources( ctx.getAssets(), dm, conf ).getString( id ) ) ) result.add( l.getLanguage() );
}
conf.locale = originalLocale;
return result;
}
where as id arg should be used a R.string.some_message which is provided in all translations and contains clearly distinguishable text, like "Do you really want to delete the object?"
Maybe it would help someone...
LocaleList or LocaleListCompat are one of the ways you could get the languages supported by your application.
LocaleList was introduced in API 24.
The thing to consider when using LocaleListCompat is that for API < 24 only the first language tag will be used.
these res-lang actually depends on Locales, so you need to get locale from device and you can get which language is getting shown from locale..
Locale myPhoneLocale = Locale.getDefault();
You can then call getDisplayLanguage() to know which language is getting shown.
Reference : Locale
Are you talking about this?
String language = Locale.getDefault().getDisplayLanguage();
Try calling AssetManager.getLocales():
Get the locales that this asset manager contains data for.
Or you can try if you can get a list using list().
Return a String array of all the assets at the given path.
Inspired with the code by#Injecteer
I have done the following:
for the list of languages that the app supports , it is necessary to pass the default language , since it is not possible to detect
public static Map<String,String> getAppLanguages(Context context, String appDefaultLang) {
Map<String, String> listAppLocales = new LinkedHashMap<>();
listAppLocales.put("default","Auto");
DisplayMetrics metrics = new DisplayMetrics();
Resources res = context.getResources();
Configuration conf = res.getConfiguration();
String[] listLocates = res.getAssets().getLocales();
for (String locate : listLocates) {
conf.locale = new Locale(locate);
Resources res1 = new Resources(context.getAssets(), metrics, conf);
String s1 = res1.getString(R.string.title_itinerary);
String value = ucfirst(conf.locale.getDisplayName());
conf.locale = new Locale("");
Resources res2 = new Resources(context.getAssets(), metrics, conf);
String s2 = res2.getString(R.string.title_itinerary);
if (!s1.equals(s2)) {
listAppLocales.put(locate, value);
} else if (locate.equals(appDefaultLang)) {
listAppLocales.put(locate, value);
}
}
return listAppLocales;
}
The result is a list map<key,value>of languages supported by the application, the first thing is for if you want to use to populate a listPreference
Do you mean:
String[] locales = getAssets().getLocales();
This would let you get the language that your device have.
Related
I have some packages with a status.
in strings xml those status would be (translated to norwegian)
<string name="collectable">Kan hentes</string>
<string name="underway">Underveis</string>
<string name="transport_to_recipient">Leveres i dag</string>
<string name="returned">Sendt i retur</string>
<string name="archived">Utlevert</string>
<string name="sent">Sendt av deg</string>
<string name="unknown">Foreløpig ukjent</string>
so in my xml layout i want to do something like this:
android:text="#{`#strings/`+ parcelListItem.status.toString()}"
so the string names would match with the text. i am also using databinding for this to get parcelitem.status.
My problem is that it just prints out "#strings/transport_to_receipient", not the actual translation. Is there a way to do this in a smart way, or should i just probably make a method on it?
You need to get the by using something like this:
public String getStringByString(String key) {
String retString = key;
int id = getResource().getIdentifier(key, "string", getPackageName());
if (id != 0) {
retString = getString(id);
}
return retString;
}
So basically this will try to get the resource name from you strings.xml file. If it fails will return the key.
To access this string <string name="transport_to_recipient">Leveres i dag</string> you need to update your resource configuration just LIKE THIS.
Resources resources= context.getResources();
Configuration configuration = resources.getConfiguration();
DisplayMetrics metrics= resources.getDisplayMetrics();
configuration.setLocale(new Locale("nb")); //country code depend on your XML
resources.updateConfiguration(configuration,metrics);
nb is country code might be in your case it will be different.
You will country code on the side of string.xml file in Resource folder.
Ended up using this method based on the answer above:
public static int getStringResourceIdByName(Context context, String stringId) {
if (Utils.isNullOrBlank(stringId))
stringId = ParcelListItem.Status.unknown.toString();
return context.getResources().getIdentifier(stringId, "string", context.getPackageName());
}
and referred like this:
Utils.getStringResourceIdByName(context, parcelListItem.status.toString())
I need to check my fragment when I change the app language.
Here is my Android Espresso test:
#Test
public void changeLanguages() {
Resources resources = context.getResources();
String[] appLanguages = resources.getStringArray(R.array.app_lang_codes);
for (int index = 0; index < appLanguages.length; index++) {
String currentLang = appLanguages[index];
Locale currentLocale = new Locale(currentLang);
if (currentLocale.equals(AppLanguageService.getLocaleRO(context))) {
// click Romanian
onView(withId(R.id.containerLanguageRO)).perform(click());
onView(withId(R.id.textViewSelectLanguage)).check(matches(withText("Selecți limba")));
} else if (currentLocale.equals(AppLanguageService.getLocaleEN(context))) {
// click English
onView(withId(R.id.containerLanguageEN)).perform(click());
onView(withId(R.id.textViewSelectLanguage)).check(matches(withText("Select language")));
}
}
}
Ant it's working fine. OK!
But as you can see I need to hard code the string for a specific language for the test.
"Selecți limba" and "Select language". And I think it's not good.
Is it possible to not use hard code strings to check that text is shown in a specific language?
You can use
mActivityRule.getActivity()
to get the activity you are testing. With this you could fetch a string from your resources like this:
mActivityRule.getActivity().getResources().getString(R.string.your_string)
You could rewrite your check like this:
onView(withId(R.id.textViewSelectLanguage)).check(matches(withText(mActivityRule.getActivity().getResources().getString(R.string.your_string))));
where your_string is the name of your string resource in your strings.xml files.
The Serbian language has Latin and Cyrillic alphabets. In Android's Date and Time Picker widgets, the displayed alphabet for Serbian locales seems to be Cyrillic, as seen here.
I wanted to change the locale so that the android widgets are using the Latin Serbian alphabet.
The current language/country code (yielding Cyrillic) are sr and RS respectively. Therefore, my setLocale function is called as
setLocale("sr", "RS");
This is the part im not sure about - according to localeplanet.com, the local code for latin serbian is sr_Latn_RS. However, I tried both
setLocale("sr_Latn", "RS");
//and
setLocale("sr_Latn_RS", "RS");
neither of which work (no change occurs, default to english). According to the Android documentation, it looks like setLocale expects two letter codes.
The language codes are two-letter lowercase ISO language codes (such
as "en") as defined by ISO 639-1. The country codes are two-letter
uppercase ISO country codes (such as "US") as defined by ISO 3166-1.
The variant codes are unspecified.
So how do I specify a Latin serbian locale code? Or does it not exist?
The previous answer works well if you only support Lollipop or above. However, if you're coding in Serbian a lot of your user base probably won't have it. Here's a solution that works for old and new versions.
private static Locale serbianLatinLocale(){
Locale locale = null;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
for (Locale checkLocale : Locale.getAvailableLocales()) {
if (checkLocale.getISO3Language().equals("srp") && checkLocale.getCountry().equals("LATN") && checkLocale.getVariant().equals("")) {
locale = checkLocale;
}
}
} else {
locale = new Locale.Builder().setLanguage("sr").setRegion("RS").setScript("Latn").build();
}
return locale;
}
For getting latin locale I first used code below.
new Locale.Builder().setLanguage("sr").setRegion("RS").setScript("Latn").build();
But this solution didn't work on my Android 5.1.1 device (it was still in cyrillic). So I removed setting of region like this:
new Locale.Builder().setLanguage("sr").setScript("Latn").build();
And you have to put your string for serbian resources in b+sr+Latn folder.
Please search for your query before posting a question. It may be answered in some other related form.
Locale newLocale = new Locale("sr","RS");
Configuration config = new Configuration();
config.setLocale(newLocale);
// using this to reference my Activity
this.getBaseContext().getResources().updateConfiguration(config, this.getBaseContext().getResources().getDisplayMetrics());
i found these two answers suitable to your query
android custom date-picker SO and locale from english to french.
EDIT
Locale[] locales = Locale.getAvailableLocales();
for(Locale locale : locales){
if(locale.getCountry().equalsIgnoreCase("RS")
&& locale.getScript().equalsIgnoreCase("Latn"))
{
Configuration config = new Configuration();
config.setLocale(locale);
// using this to reference my Activity
this.getBaseContext().getResources().updateConfiguration(config, this.getBaseContext().getResources().getDisplayMetrics());
break;
}
}
I know there will be an efficient way to do it, however you may get the direction that you need to get the list of available locales and get the locale you desire. Hope it helps
EDIT-2 (Final)
you can construct the locale using:
Locale locale = new Locale.Builder().setLanguage("sr").setRegion("RS").setScript("Latn").build();
setLocale(locale);
Can you please use below one ?
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
Resources res = this.getResources();
Configuration conf = res.getConfiguration();
boolean isLatinAlphabet = PreferenceManager.getDefaultSharedPreferences(this);
if(conf.locale.getLanguage().equals("sr") && isLatinAlphabet) {
conf.locale = new Locale("sr", "YourContryCode");
res.updateConfiguration(conf, res.getDisplayMetrics());
}
}
}
Note: Replace your YourContryCode in conf.locale = new Locale("sr", "YourContryCode"); line.
Manifest.xml:
<application
android:name=".MyApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/application_name"
android:theme="#style/AppTheme">
...
</application>
Hope this will help you.
How can I get simplified chinese description (简体)? From the available locale Locale.SIMPLIFIED_CHINESE, no method seems to return this description:
getDisplayLanguage() returns the correct language name, but without the variant.
getDisplayName() returns the correct language name and country, but also without the variant.
getDisplayVariant() returns an empty string.
I've also tried to build a new Locale using the different constructors, also to no avail.
new Locale("zh", "CN");
new Locale("zh", "CN", "Hans");
I've checked the Android source code for LocalePicker and I've concluded that it is loaded from the resources (special_locale_codes and special_locale_names).
Any solutions besides having to hardcode/include this string in my resources?
Let me explain my process on how I tackled this. First, I found this block of code in LocalePicker.java
private static String getDisplayName(Locale l, String[] specialLocaleCodes, String[] specialLocaleNames) {
String code = l.toString();
for (int i = 0; i < specialLocaleCodes.length; i++) {
if (specialLocaleCodes[i].equals(code)) {
return specialLocaleNames[i];
}
}
return l.getDisplayName(l);
}
which takes in a Locale as you already know. Then it tries to find the locale code in the specialLocaleCodes string array. The specialLocaleNames you are seeking are obtained from arrays.xml as you've helpfully stated:
<string-array translatable="false" name="special_locale_codes">
<item>ar_EG</item>
<item>zh_CN</item>
<item>zh_TW</item>
</string-array>
and the corresponding languages
<string-array translatable="false" name="special_locale_names">
<item>العربية</item>
<item>中文 (简体)</item>
<item>中文 (繁體)</item>
</string-array>
Notice the code with the simplified Chinese is zh_CN and the last two characters are capitalized.
However,
Locale locale = new Locale("zh_CN");
System.out.println("Locale: " + locale);
prints
Locale: zh_cn
Notice the lower case. So there is no way specialLocaleCodes[i].equals(code) will return true. So then I poked around Locale.java and, long story short, we can bypass that case-changing jumble by doing this (and you MUST keep the 3rd parameter as an empty string for this to work):
Locale locale = new Locale("zh", "CN", "");
System.out.println("Locale: " + locale);
Prints
Locale: zh_CN
With this you should be able to do this:
Locale locale = new Locale("zh", "CN", "");
System.out.println("Name:" + locale.getDisplayName(locale));
Upon further inspection on Kitkat using this (thank you Andrew!)
int specialLocaleNamesId = Resources.getSystem().getIdentifier("special_locale_names", "array", "android");
String[] specialLocaleNames = Resources.getSystem().getStringArray(specialLocaleNamesId);
it was possible to print out
العربية,中文 (简体),中文 (繁體)
as expected. However, something in Kitkat is still preventing the correct string to display. Frustrating.
However, in Lollipop 5.0+ and Java 1.7 this works using forLanguageTag() in Locale.
Locale locale = Locale.forLanguageTag("zh-Hans");
System.out.println("getDisplayName:" + locale.getDisplayName(locale));
System.out.println("getDisplayLanguage:" + locale.getDisplayLanguage(locale));
which prints
getDisplayName:中文 (简体中文)
getDisplayLanguage:中文
You could probably access the android internal resource: com.android.internal.R.array.special_locale_names the same way it's done in LocalePicker:
final Resources resources = context.getResources();
final String[] specialLocaleNames = resources.getStringArray(com.android.internal.R.array.special_locale_names);
But it's probably safer to use your own resource here (avoiding
the use of internals)
I am asking if There is a way to force the android application to read from Arabic layout folders and Arabic values folder whatever the device language ?
You can force a different locale like this:
protected static void setLocale(final Context ctx, final String lang)
{
final Locale loc = new Locale(lang);
Locale.setDefault(loc);
final Configuration cfg = new Configuration();
cfg.locale = loc;
ctx.getResources().updateConfiguration(cfg, null);
}
In your case, use it so
setLocale(getApplicationContext(), "ar")
This will take the values from your "ar" folders (drawables-ar, values-ar, layout-ar, ...)