String Resources

A resource in Android is a file (like a music file) or a value (like the title of a dialog box) that is bound to an executable application. These files and values are bound to the executable in such a way that you can change them without recompiling and redeploying the application.

Resources play a part in many, if not all, familiar UI frameworks. Familiar examples of resources include strings, colors, and bitmaps. Instead of hard-coding strings in an application, for example, you can use their IDs instead. This indirection lets you change the text of the string resource without changing the source code.

Let's start with strings and see how they are used as resources. Android allows you to define multiple strings in one or more XML resource files. These XML files containing string-resource definitions reside in the /res/values subdirectory. The names of the XML files are arbitrary, although you will commonly see the file name as strings.xml. Listing 3-1 shows an example of a string-resource file.

Listing 3-1. Example strings.xml File

<?xml version="1.0" encoding="utf-8"?> <resources>

<string name="hello">hello</string> <string name="app_name">hello appname</string> </resources>

When this file is created or updated, the Eclipse ADT plug-in will automatically update a Java class in your application's root package called R.java with unique IDs for the two string resources specified.

Note Regardless of the number of resource files, there is only one R.java file. In releases 1.5 and up the file R.java is generated in a separate subdirectory at the same level as the Java source-code root for your application. This generated separate subdirectory is called "gen." Under this subdirectory the package name in R.java continues to be the same as in previous releases, which is the root package name for your application.

For the string-resource file in Listing 3-1, the updated R.java file would have these entries:

public final class R {

...other entries depending on your project and application public static final class string

...other entries depending on your project and application

0 0

Post a comment