问题
Can someone please explain the xliff:g
for strings/localization.
I understand that xliff:g
is not supposed to translate anything inside the <>
things, but I'm confused how exactly I'd use this in code.
An example I have in my case is the practice spanish translations that I have has:
<string name="order_quantity">Cantidad: <xliff:g id="quantity" example="2">%d/xliff:g</string>
I am now trying to get localized strings with xliff:g
to work.
What is id
here and what does it do? And what does it call?
Also what is the %d
and what does it do? What is the point of example
? Also, how would I call that into code, if at all?
Why can't someone just do the following code to insert the following xml:
<string name="quant">Quantity: </string>
into java like so:
getString(R.string.quant) + quantity
so that way it concactenates the quantity variable into the getString
?
回答1:
Minor typo in your example, there should be a closing tag:
<string name="order_quantity">Cantidad: <xliff:g id="quantity" example="2">%d</xliff:g></string>
The id
attribute is just used to identify what the substitution parameter represents (in your case, it represents the quantity). It's as you said, a note, and not actually used programmatically.
That said, in Android Studio, if you have Code Folding enabled for strings, it will substitute in the ID when it shows the collapsed string. You'd see something like this:
// This...
mTextView.setText(getString(R.string.order_quantity, 2));
// Will show as this when folded:
mTextView.setText("Cantidad: {quantity}");
As for your second question, why not just use string concatenation? In other languages, the substitution may not go at the end of the string. You could have something like:
values/strings.xml
<string name="order_quantity">%d items</string>
values-es/strings.xml
<string name="order_quantity">Cantidad: %d</string>
So you can see that in this case, simply appending the strings together would not give you a valid result.
回答2:
%d is used to represent a part of memory as an integer. It's most commonly used to print some number to standard output, as follows:
#include <stdio.h>
int main()
{
int n = 42;
printf("The answer to life, universe and everything is %d", n);
return 0;
}
Unlike Java, where you simply concatenate numbers and strings etc., C uses this %something to indicate what is being written. %d indicates, that for example in the printf(), after the comma there will be an argument (in our case it's n), which should be represented as an int.
Refer to List of all format specifiers in C programming for a complete list of format specifiers
Also refer to Official Android Developers Documentation
来源:https://stackoverflow.com/questions/35004433/how-to-use-android-xliffg