Working with Strings

You can use string resources anywhere your application needs to display text. You tag string resources with the <string> tag and store them in the resource file /res/values/strings.xml.

Here is an example of a string resource file:

<?xml version="i.0" encoding="utf-8"?> <resources>

<string name="app_name">Name this App</string> <string name="hello">Hello</string> </resources>

String resources have a number of formatting options. Table 4.1 shows some simple examples of well-formatted string values.

Strings that contain apostrophes or single straight quotes must be escaped or wrapped within double straight quotes.

TABLE 4.1 String Resource Formatting Examples String Resource Value Will Be Displayed As

Hello, World Hello, World

"Hello, World" Hello, World

Mother\'s Maiden Name: Mother's Maiden Name:

He said, \"No.\" He said, "No."

There are several ways to access a string resource programmatically. The simplest way is to use the getString() method:

String greeting = getResources().getString(R.string.hello);

0 0

Post a comment