Note Unlike other UI frameworks Android offers the ability to quickly associate IDs with string resources through Rjava So using strings as resources is that much easier in Android

Let us start by showing how you can define normal strings, quoted strings, HTML strings, and substitutable strings in an XML resource file (see Listing 3-6).

Listing 3-6. XML Syntax for Defining String Resources <resources>

<string name="simple_string">simple string</string> <string name="quoted_string">"quoted'string"</string> <string name="double_quoted_string">\"double quotes\"</string> <string name="java_format_string">

hello %2$s java format string. %1$s again </string>

<string name="tagged_string">

Hello <b><i>Slanted Android</i></b>, You are bold. </string> </resources>

This XML string-resource file needs to be in the /res/values subdirectory. The name of the file is arbitrary.

Notice how quoted strings need to be either escaped or placed in alternate quotes. The string definitions also allow standard Java string-formatting sequences.

Android also allows child XML elements such as <b>, <i>, and other simple text-formatting HTML within the <string> node. You can use this compound HTML string to style the text before painting in a text view.

The Java examples in Listing 3-7 illustrate each usage.

Listing 3-7. Using String Resources in Java Code

//Read a simple string and set it in a text view

String simpleString = activity.getString(R.string.simple_string);

textView.setText(simpleString);

0 0

Post a comment