Help with Localization for Android

Embedding HTML in String resources and using it from Java

How does escaping HTML for XML work?There are five special characters in XML which you have to escape if you do not want their special function. These are:' single quote" double quote< less-than> greater-than& ampersandYou can escape them either by wrapping them inside <![CDATA[...]]> or by replacing them with their respective XML entities.

Do I always have to escape my HTML inside XML?If you want to preserve the HTML, for example if you want to show the HTML code on screen, yes.If you want to use HTML in order to style your text for use in TextViews, it depends, as there are two ways to do this:

Approach A: Leave HTML unescaped and call getText(...)You can embed your HTML code in XML without escaping it, but then you must call getText(...) instead of getString(...) from Java. The advantage is that this approach is very easy, you do not need any escaping and you can just as well reference the HTML strings from XML layout files without losing the text styling.

Approach B: Escape HTML and call Html.fromHtml(getText(...))If you escape your HTML by using CDATA sections or by escaping the single characters, you have to call Html.fromHtml(getText(...)) from Java if you want to get the styled text.

Which HTML tags can I use?You can only be sure about <b>, <i> and <u>. These will (almost) always work. Others may work on some devices, but usually they do not.

What does that mean for me?Localize takes care of all the text processing and escaping for you. When exporting your translations to XML files, you can choose between approaches A (getText(...)) and B (Html.fromHtml(getString(...))) for your project.

Resource value

Java method

Displayed result

<b>Lorem</b> ipsum <button>dolor</button> sit

getString(...)

Lorem ipsum dolor sit

<b>Lorem</b> ipsum <button>dolor</button> sit

getText(...)

Lorem ipsum dolor sit

<b>Lorem</b> ipsum <button>dolor</button> sit

Html.fromHtml(getString(...))

Lorem ipsum dolor sit

&lt;b&gt;Lorem&lt;/b&gt; ipsum &lt;button&gt;dolor&lt;/button&gt; sit

getString(...)

<b>Lorem</b> ipsum <button>dolor</button> sit

&lt;b&gt;Lorem&lt;/b&gt; ipsum &lt;button&gt;dolor&lt;/button&gt; sit

getText(...)

<b>Lorem</b> ipsum <button>dolor</button> sit

&lt;b&gt;Lorem&lt;/b&gt; ipsum &lt;button&gt;dolor&lt;/button&gt; sit

Html.fromHtml(getString(...))

Lorem ipsum dolor sit

<![CDATA[<b>Lorem</b> ipsum <button>dolor</button> sit]]>

getString(...)

<b>Lorem</b> ipsum <button>dolor</button> sit

<![CDATA[<b>Lorem</b> ipsum <button>dolor</button> sit]]>

getText(...)

<b>Lorem</b> ipsum <button>dolor</button> sit

<![CDATA[<b>Lorem</b> ipsum <button>dolor</button> sit]]>

Html.fromHtml(getString(...))

Lorem ipsum dolor sit

Providing a custom language selection in Android

Use the following string-array as the resource for your human-readable preference options. You can use ListPreference's android:entries, for example.