Android translation at runtime - android

Is there a way in Android to translate strings with an own translation file at runtime?
e.g.
english file:
hello world : Hello world.
german file:
hello world: Hallo Welt.
Like in Webframeworks (Symfony, Rails, ...)

I can think of two ways to do so. One is to specify the Android language/region code and use different res/values/strings.xml to translate the string values. But this will affect the entire app. Here is the reference on supporting different languages
Another way to do so is to create localized resource file like this for server response translation.
So the strings.xml would be like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="error_msg_ge">Fehlermeldung</string>
<string name="error_msg_en">Error Message</string>
</resources>
Below is just a pseudo code since you didn't post any code.
if(!isSuccess) {
TextView textView = new TextView(this);
textView.setText(R.string.error_msg_ge)
}
If we really want to be more precise, then we can specify more error messages in the resource file and swap to use based on the error message returned from the server.
So the XML could be like this
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="error_ge_timeout">auszeit</string>
<string name="error_ge_noresult">kein Ergebnis</string>
<string name="error_en_timeout">timeout</string>
<string name="error_en_noresult">no result</string>
</resources>
Then
if(!isSuccess) {
TextView textView = new TextView(this);
if(errMsg.equals(R.string.error_en_timeout)) {
textView.setText(R.string.error_ge_timeout);
} //...and so on
}
Lastly but not the least, you can also utilize third party API to do the translation. But since you are translating error message received from the server, I am not sure if that is necessary since it is not a conversational purpose so it could be an overkill. In any case, there are many ways to achieve it.

Related

Android strings xml similar texts

In my Android app I'm using strings.xml for all texts. I have many situations where I use almost the same string,
e.g. "Name" and "Name:" - translation is the same only additional colon is difference.
Is there any other way to have these two string except creating two string items like this:
<string name="name">Name</string>
<string name="name2">Name:</string>
There is no way you can concatenate strings in the strings.xml file.
All you can do is specify the format,
<string name="name">Name</string>
<string name="string_with_colon">%s:</string>
Then pass the name programatically,
String.format(getString(R.string.string_with_colon), getString(R.string.name));
Yes, you can do so without writing any Java/Kotlin code, only XML by using this small library I created which does so at buildtime: https://github.com/LikeTheSalad/android-stem
Usage
Based on your example, you'd have to set your strings like this:
<string name="name">Name</string>
<string name="name2">${name}:</string>
And then after building your project, you'll get:
<!-- Auto generated during compilation -->
<string name="name2">Name:</string>

Compare Android String xml files

I have two string xml for two different languages, I would like to know the different between those xml files.
For example, there is one xml for English,
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Keep Accounts</string>
<string name="insertNewOne">Insert Accounts</string>
<string name="browseRecord">Browse Records</string>
<string name="set">Setting</string>
</resources>
And another xml for other language,
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Example</string>
<string name="insertNewOne">Example</string>
<string name="browseRecord">Example</string>
<string name="dateNoColon">Example</string>
</resources>
We can see the difference is xml for English has element string name="set", and the other has not. On the other hand, the xml file for other language has element string name="dateNoColon" but the xml for English has not.
In this case, I would like to know the English xml lacks the element string name="dateNoColon", and other xml lacks the element string name="set".
Android Studio has translations editor starting of 0.8.12 version. You can find there missing translation strings.
You can enable check for missing translations in Lint tool. There are "Missing translation" and "Extra translation" checks.
Extra translation If a string appears in a specific language translation file, but there is no corresponding string in the default locale, then this string is probably unused. (It's technically possible that your application is only intended to run in a specific locale, but it's still a good idea to provide a fallback.).
Incomplete translation If an application has more than one locale, then all the strings declared in one language should also be translated in all other languages.
Suppose if the device is set to Other language, Android will look for title in the otherlanguage.xml file in value folder. But if no such string is included in that file, Android will fall back to the default, and will load title in English from the english.xml file.
For more detail go to http://developer.android.com/guide/topics/resources/localization.html#using-framework
I wrote a small tool for that: resdiff.
Check it out! https://github.com/danijoo/resdiff
Try sorting both files using some perl or bash script or something like that for example, using bash:
sort temp.txt -o temp.txt
and then look at the diff for example using DiffMergeit.
Use Android Lint to find both incomplete translations i.e. strings missing in a language variant and extra translations i.e. strings introduced in a language variant but missing in the default locale.
In Android Studio you can run Lint (and some other analysis tools) with Analyze -> Inspect Code.

Is concatenation of resource strings/string concatenation, possible in layout file?

I have resource strings :
<string name="address">Address</string>
<string name="city">City</string>
<string name="country">Country</string>
<string name="pincode">Pincode</string>
In my application, at few places I am using these strings alone and at few places I am succeeding them by a colon.
I don't what to create another four resource strings :
<string name="address_with_colon">Address: </string>
<string name="city_with_colon">City: </string>
<string name="country_with_colon">Country: </string>
<string name="pincode_with_colon">Pincode: </string>
Now to achieve this, I have to concatenate my resource strings with colon. I know this is very easy though java code which I can write in my activity class. But what I want is to do the concatenation in my layout file.
Question : Is string concatenation possible in layout file?
This is where I have to perform the concatenation:
android:text="concatenation_if_possible"
Using XML entities it's possible to use the same string multiple places within an XML file:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE resources [
<!ENTITY appname "MrQuery">
<!ENTITY author "Oded">
]>
<resources>
<string name="app_name">&appname;</string>
<string name="description">The &appname; app was created by &author;</string>
</resources>
I used this answer: dynamic String using String.xml?
Question : Is string concatenation possible in layout file?
Nope as far as I know.
One solution is to use what #DIVA has answered before.
Another possible solution is to create a custom view that extends TextView (or the view you want to achieve this) and create a custom attribute custom:concatenate which receives a string reference and perform the concatenation automatically. IMHO I think this is the most clean approach.
In code will look as this:
<com.whatever.ConcatenateTextView
android:text="#string/whatever"
custom:concatenate="#string/second_string"/>
Or… you can use the power of Drawables creating a custom TextDrawable (which is explained very well by #Devunwired in this post and the concrete implementation of it in Github).
Copying what #Devunwired has said in his post about it:
With this class, text can now be part of the Drawable world, meaning it can not only be set alone in places where you would normally put an image, it can also be placed together with other Drawables in containers like StateListDrawable or animated with the likes of TransitionDrawable and ClipDrawable. In many cases, we can use this to do a job that would otherwise require multiple views or compound controls just to achieve a given visual effect; thus it can reduce overhead in your view hierarchy.
This combined with your custom TextView as I explained before (or whatever view you want to use) gives you a very powerful option. Again copying the example that #Devunwired wrote in his post:
ImageView mImageOne;
TextDrawable d = new TextDrawable(this);
d.setText("SAMPLE TEXT\nLINE TWO");
d.setTextAlign(Layout.Alignment.ALIGN_CENTER);
mImageOne.setImageDrawable(d);
If you need more help please let me know in the comments and I'll gladly update the answer!
You can so something like this :
<string name="meatShootingMessage">You shot %1$d pounds of meat!</string>
String strMeatMsg = String.format(strMeatFormat, ":");
textview.setText(strMeatMsg);
No, you cannot concatenate several string resources into a single string when directly referencing those strings from a layout file.
XML layout files are simply a template of instructions for Android to build a user interface, and you should consider them as a cleaner and more organized way to generate your UI than using a Java class that manually creates and positions views in a layout. That being said, there are limitations to what you can do with a layout file, and one of them is being able to reference a single string resource from every view, meaning that you can't do anything more complex than that, including concatenating several strings into one.
You can do so using this plugin I've created: https://github.com/LikeTheSalad/android-stem It will concat all of the strings you'd like to and will generate at build time a final XML string that you can reference anywhere as with any other manually string you've added.
For your case, you can do the following:
<string name="address">Address</string>
<string name="city">City</string>
<string name="country">Country</string>
<string name="pincode">Pincode</string>
<string name="address_with_colon">${address}: </string>
<string name="city_with_colon">${city}: </string>
<string name="country_with_colon">${country}: </string>
<string name="pincode_with_colon">${pincode}: </string>
And then the tool will generate:
<!-- Auto generated during compilation -->
<string name="address_with_colon">Address: </string>
<string name="city_with_colon">City: </string>
<string name="country_with_colon">Country: </string>
<string name="pincode_with_colon">Pincode: </string>
And anytime you decide to change either your template or values strings, the plugin will keep the generated strings updated. More info on the repo's page.

Android: text from strings.xml displayed as #numbers

I have updated some string values in strings.xml and my application now shows not the new text but something like #234545201. I have cleaned the projected and rebuilded, there are no import android.R anywhere, just R related to my package. What went wrong?
To obtain a string from your strings.xml file, you can do a few things.
If you need it as a String object, you can use getString(R.string.string_id) to fetch the string, given an ID.
If you're trying to set the text of, say, a TextView, you can actually simply use setText(R.string.string_id) and the OS will obtain the correct string for you.
In other words, the TextView class has a method called setText(int resid), and that's also the reason why you can't write something like the following:
TextView.setText(12345680);
Are you trying to read it directly as R.string.my_string_resource?
Try passing it to getString() as getString(R.string.my_string_resource).
You can put your stings.xml file in the follwing format.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Yamba</string>
<string name="titleYamba">Yamba</string>
<string name="titleStatus">Status Update</string>
<string name="hintText">Please enter your 140-character status</string>
<string name="buttonUpdate">Update</string>
</resources>
and use the name as reference of your textbox ids like.
android:text="#string/app_name"

Android dynamically create String Array from XML string resources, without XML string array

Ok, so this question is a bit weird, and kinda rubs me the wrong to even ask, but since I probably don't have a choice I want to see what you guys think. I'm still a novice at Java and Android.
The case is as follows: We are trying to automate the building of our strings.xml for localisation. A parser has been made to convert a csv-file to xml. For regular strings it's not a real problem, that works fine. But the parser that was built, doesn't take string arrays into account and there is little chance that someone will modify it.
Is there an "easy" way to work with the strings and create an string array programmatically based on parts the name attributes?
If not, then I would have to hard code the arrays and that leaves the creator (client) of the language files unable to add items to something that should be a dynamic list.
I know modifying the strings.xml manually might be an option, but because our management wants to automate stuff like that, it's not much of a choice I have.
Probably I will hard code the stuff and say they can't dynamically fill the lists, but still (also for my personal education) I wanna know what you guys think.
Thanks for your opinions or solutions. :)
Cheers!
You can use (& really really really should anyways) references in string arrays. Assuming this is your generated res/values/strings.xml in Swedish:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="string1">Hej, detta är på svenska</string>
<string name="string2">Denna strängen också</string>
</resources>
You can put your string-array in, for instance, res/values/arrays.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="somearrayname">
<item>#string/string1</item>
<item>#string/string1</item>
</string-array>
</resources>
So you will get strings.xml as below
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="string1">1st string</string>
<string name="string2">2nd string</string>
........
<string name="stringN">Nth string</string>
</resources>
I suggest a simple modification to strings.xml, which is add a string with name count at top of all strings with value equal to total number of strings and add another string with name prefix below the count, then it looks like as below.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="count">4</string>
<string name="prefix">string</string>
<string name="string1">1st string</string>
<string name="string2">2nd string</string>
<string name="string3">3rd string</string>
<string name="string4">4th string</string>
</resources>
So now, in your java file you can access them like below
int count = Integer.parseInt(getString(R.string.count));
String prefix = getString(R.string.prefix);
String[] strings = new String[count];
for (int i = 0; i < count; i++) {
strings[i] = getString(getResources().getIdentifier(prefix+(i+1), "string", getPackageName()));
}
I hope it may help you.

Categories

Resources