How to use Android xliff:g

Tal C picture Tal C · Jan 26, 2016 · Viewed 17.4k times · Source

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?

Answer

Kevin Coppock picture Kevin Coppock · Jan 26, 2016

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.