Working with Resources Android

In this section, we look at the specific types of resources available for Android applications, how they are defined in the project files, and how you can access this resource data programma- tically.

For each type of resource type, you learn what types of values can be stored and in what format. Some resource types (such as Strings and Colors) are well supported with the Android Plug-in Resource Editor, whereas others (such as Animation sequences) are more easily managed by editing the XML files directly.

Working with String Resources

String resources are among the simplest resource types available to the developer. String resources might show text labels on form views and for help text.The application name is also stored as a string resource, by default.

String resources are defined in XML under the /res/values project directory and compiled into the application package at build time. All strings with apostrophes or single straight quotes need to be escaped or wrapped in double straight quotes. Some examples of well-formatted string values are shown in Table.

String Resource Formatting Examples

String Resource Formatting Examples

You can edit the strings.xml file using the Resources tab, or you can edit the XML directly by clicking the file and choosing the strings.xml tab. After you save the file, the resources are automatically added to your R.java class file.

String values are appropriately tagged with the <string> tag and represent a namevalue pair. The name attribute is how you refer to the specific string programmatically, so name these resources wisely.

Here’s an example of the string resource file /res/values/strings.xml:

Bold, Italic,and Underlined Strings

You can also add three HTML-style attributes to string resources. These are bold, italic,and underlining. You specify the styling using the <b>, <i>, and <u> tags. For example

Using String Resources as Format Strings

You can create format strings, but you need to escape all bold, italic, and underlining tags if you do so. For example, this text shows a score and the “win” or “lose” string:

If you want to include bold, italic, or underlining in this format string, you need to escape the format tags. For example, if want to italicize the “win” or “lose” string at the end, your resource would look like this:

Using String Resources Programmatically

As shown earlier in this chapter, accessing string resources in code is straightforward. There are two primary ways in which you can access this string resource.

The following code accesses your application’s string resource named hello, returning only the string. All HTML-style attributes (bold, italic, and underlining) are stripped from the string.

You can also access the string and preserve the formatting by using this other method:

To load a format string, you need to make sure any format variables are properly escaped.One way you can do this is by using the TextUtils.htmlEncode() method:

The resulting text in the resultText variable is

Score: 5 of 5! You Won.

Now if you have styling in this format string like the preceding winLoseStyled string resource, you need to take a few more steps to handle the escaped italic tags.

Theresulting text in the styledResults variable is

Score: 5 of 5! You <i>won</i>.

This variable, styledResults, can then be used in user interface controls such as TextView objects, where styled text is displayed correctly.

Working with String Arrays

You can specify lists of strings in resource files. This can be a good way to store menu options and drop-down list values. String arrays are defined in XML under the /res/values project directory and compiled into the application package at build time.String arrays are appropriately tagged with the <string-array> tag and a number of <item> child tags, one for each string in the array. Here’s an example of a simple array resource file /res /values /arrays .xml:

As shown earlier in this chapter, accessing string arrays resources is easy. The following code retrieves a string array named flavors:

Working with Boolean Resources

Other primitive types are supported by the Android resource hierarchy as well. Boolean resources can be used to store information about application game preferences and default values. Boolean resources are defined in XML under the /res/values project directory and compiled into the application package at build time.

Defining Boolean Resources in XML

Boolean values are appropriately tagged with the <bool> tag and represent a name value pair. The name attribute is how you refer to the specific Boolean value programmatically, so name these resources wisely.

Here’s an example of the Boolean resource file /res/values/bools.xml:

Using Boolean Resources Programmatically

To use a Boolean resource,you must load it using the Resource class.The following code accesses your application’s Boolean resource named bAdvancedFeaturesEnabled.

Working with Integer Resources

In addition to strings and Boolean values, you can also store integers as resources.Integer resources are defined in XML under the /res/values project directory and compiled into the application package at build time.

Defining Integer Resources in XML

Integer values are appropriately tagged with the <integer> tag and represent a name value pair. The name attribute is how you refer to the specific integer programmatically, so name these resources wisely.

Here’s an example of the integer resource file /res/values/nums.xml:

Using Integer Resources Programmatically

To use the integer resource, you must load it using the Resource class. The following code accesses your application’s integer resource named numTimesToRepeat:

Working with Colors

Android applications can store RGB color values, which can then be applied to other screen elements. You can use these values to set the color of text or other elements, such as the screen background. Color resources are defined in XML under the /res/values project directory and compiled into the application package at build time.

RGB color values always start with the hash symbol (#).The alpha value can be given for transparency control. The following color formats are supported:

  • #RGB (example, #F00 is 12-bit color, red)
  • #ARGB example, #8F00 is 12-bit color, red with alpha 50%)
  • #RRGGBB (example, #FF00FF is 24-bit color, magenta)
  • #AARRGGBB example, #80FF00FF is 24-bit color, magenta with alpha 50%)

Color values are appropriately tagged with the <color> tag and represent a name-value pair. Here’s an example of a simple color resource file /res /values /colors .xml:

The example at the beginning of the chapter accessed a color resource. Color resources are simply integers.The following code retrieves a color resource called prettyTextColor:

int myResourceColor =getResources().getColor(R.color.prettyTextColor);

Working with Dimensions

Many user interface layout controls such as text controls and buttons are drawn to specific dimensions. These dimensions can be stored as resources. Dimension values always end with a unit of measurement tag.

Dimension values are appropriately tagged with the <dimen> tag and represent a name value pair. Dimension resources are defined in XML under the /res/values project directory and compiled into the application package at build time.

The dimension units supported are shown in Table.

Dimension Unit Measurements Supported

Dimension Unit Measurements Supported

Here’s an example of a simple dimension resource file /res/values/dimens.xml:

Dimension resources are simply floating point values.The following code retrieves a dimension resource called textPointSize:

Working with Simple Drawables

You can specify simple colored rectangles by using the drawable resource type, which can then be applied to other screen elements. These drawable types are defined in specific paint colors, much like the Color resources are defined.

Simple paintable drawable resources are defined in XML under the /res/values project directory and compiled into the application package at build time. Paintable drawable resources use the <drawable> tag and represent a name-value pair. Here’s an example of a simple drawable resource file /res/values/drawables.xml:

Although it might seem a tad confusing, you can also create XML files that describe other Drawable subclasses, such as ShapeDrawable. Drawable XML definition files are stored in the /res/drawable directory within your project along with image files. This is not the same as storing <drawable> resources, which are paintable drawables.PaintableDrawable resources are stored in the /res/values directory, as explained in the previous section.

Here’s a simple ShapeDrawable described in the file /res/drawable/red_oval.xml:

We talk more about graphics and drawing shapes in Chapter “Drawing and Working with Animation.”

Drawable resources defined with <drawable> are simply rectangles of a given color,which is represented by the Drawable subclass ColorDrawable. The following code retrieves a ColorDrawable resource called redDrawable:

Working with Images

Applications often include visual elements such as icons and graphics. Android supports several image formats that can be directly included as resources for your application. These image formats are shown in Table.

Image Formats Supported in Android

Image Formats Supported in Android

Image Formats Supported in Android

These image formats are all well supported by popular graphics editors such as Adobe Photoshop, GIMP, and Microsoft Paint. The Nine-Patch Stretchable Graphics can be created from PNG files using the draw9patch tool included with the Android SDK under the /tools directory.

Adding image resources to your project is easy. Simply drag the image asset into the /res/drawable directory, and it is automatically included in the application package at build time.

Working with Nine-Patch Stretchable Graphics

Phone screens come in various dimensions. It can be handy to use stretchable graphics to allow a single graphic that can scale appropriately for different screen sizes and orientations or different lengths of text. This can save you or your designer a lot of time in creating graphics for many different screen sizes.

Android supports Nine-Patch Stretchable Graphics for this purpose. Nine-Patch graphics are simply PNG graphics that have patches, or areas of the image, defined to scale appropriately, instead of scaling the entire image as one unit. Often the center segment is transparent.

Nine-Patch Stretchable Graphics can be created from PNG files using the draw9patch tool included with the Tools directory of the Android SDK.

Using Image Resources Programmatically

Images resources are simply another kind of Drawable called a BitmapDrawable. Most of the time, you need only the resource ID of the image to set as an attribute on a user interface control.

For example,if I drop the graphics file flag.png into the /res /drawable directory and add an Image View control to my main layout,we can set the image to be displayed programmatically in the layout this way:

If you want to access the BitmapDrawable object directly, you simply request that resource directly, as follows:

Finally, if you work with Nine-Patch graphics, the call to getDrawable()returns a Nine Patch Drawable instead of a Bitmap Drawable object.

Working with Animation

Android supports frame-by-frame animation and tweening. Frame-by-frame animation involves the display of a sequence of images in rapid succession. Tweened animation involves applying standard graphical transformations such as rotations and fades upon a single image.

The Android SDK provides some helper utilities for loading and using animation resources. These utilities are found in the android. view. animation. AnimationUtils class.

For now, let’s just look at how you define animation data in terms of resources.

Defining and Using Frame-by-Frame Animation Resources

Frame-by-frame animation is often used when the content changes from frame to frame. This type of animation can be used for complex frame transitions—much like a kid’s flip-book.

To define frame-by-frame resources, take the following steps:

  1. Save each frame graphic as an individual drawable resource. It may help to name your graphics sequentially, in the order in which they are displayed—for example, frame1.png, frame2.png, and so on.
  2. Define the animation set resource in an XML file within /res/drawable/ resource directory.
  3. Load, start, and stop the animation programmatically.

Here’s an example of a simple frame-by-frame animation resource file /res /drawable/ juggle .xml that defines a simple three-frame animation that takes 1.5 seconds:

Frame-by-frame animation set resources defined with <animation-list> are represented by the Drawable subclass AnimationDrawable.The following code retrieves an Animation-Drawable resource called juggle:

After you have a valid AnimationDrawable, you can assign it to a View on the screen and use the Animation methods to start and stop animation.

Defining and Using Tweened Animation Resources

Tweened animation features include scaling, fading, rotation, and translation. These actions can be applied simultaneously or sequentially and might use different interpolators. Tweened animation sequences are not tied to a specific graphic file, so you can write one sequence and then use it for a variety of different graphics. For example, you can make moon, star, and diamond graphics all pulse using a single scaling sequence, or you can make them spin using a rotate sequence.

Graphic animation sequences can be stored as specially formatted XML files in the /res/anim directory and are compiled into the application binary at build time.

Here’s an example of a simple animation resource file /res/anim/spin.xml that defines a simple rotate operation—rotating the target graphic counterclockwise four times in place, taking 10 seconds to complete:

If we go back to the example of a BitmapDrawable earlier, we can now add some animation simply by adding the following code to load the animation resource file spin.xml and set the animation in motion:

Now you have your graphic spinning. Notice that we loaded the animation using the base class object Animation. You can also extract specific animation types using the subclasses that match: RotateAnimation, ScaleAnimation, TranslateAnimation, and AlphaAnimation.

There are a number of different interpolators you can use with your tweened animation sequences.

Working with Menus

You can also include menu resources in your project files. Like animation resources, menu resources are not tied to a specific control but can be reused in any menu control.

Each menu resource (which is a set of individual menu items) is stored as a specially formatted XML files in the /res/menu directory and are compiled into the application package at build time.

Here’s an example of a simple menu resource file /res/menu/speed.xml that defines a short menu with four items in a specific order:

You can create menus using the Eclipse plug-in, which can access the various configuration attributes for each menu item. In the previous case, we set the title (label)of each menu item and the order in which the items display. Now, you can use string resources for those titles, instead of typing in the strings. For example:

That’s it. Now if you run your application and press the menu button, you see the menu. There are a number of other XML attributes that can be assigned to menu items. For a complete list of these attributes, see the Android SDK reference for menu resources at the website.You learn a lot more about menus and menu event handling in Chapter “Exploring User Interface Screen Elements.”

Working with XML Files

You can include arbitrary XML resource files to your project. You should store these XML files in the /res/xml directory, and they are compiled into the application package at build time.

The Android SDK has a variety of packages and classes available for XML manipulation. You learn more about XML handling in Chapter “Using Android Data and Storage APIs,” Chapter “Sharing Data Between Applications with Content Providers,” and Chapter “Using Android Networking APIs.” For now, we create an XML resource file and access it through code.

First, put a simple XML file in /res/xml directory. In this case, the file my_pets.xml with the following contents can be created:

Now you can access this XML file as a resource programmatically in the following manner:

Finally, to prove this is XML, here’s one way you might churn through the XML and extract the information:

Working with Raw Files

Your application can also include raw files as part of its resources. For example, your application might use raw files such as audio files, video files, and other file formats not supported by the Android Resource packaging tool aapt.

All raw resource files are included in the /res/raw directory and are added to your package without further processing.

The resource filename must be unique to the directory and should be descriptive because the filename (without the extension) becomes the name by which the resource is accessed.

You can access raw file resources and any resource from the /res/drawable directory (bitmap graphics files, anything not using the <resource> XML definition method). Here’s one way to open a file called the_help.txt:

References to Resources

You can reference resources instead of duplicating them. For example, your application might want to reference a single string resource in multiple string arrays.

The most common use of resource references is in layout XML files, where layouts can reference any number of resources to specify attributes for layout colors, dimensions, strings, and graphics.Another common use is within style and theme resources.

Resources are referenced using the following format:

Recall that earlier we had a string-array of soup names. If we want to localize the soup listing, a better way to create the array is to create individual string resources for each soup name and then store the references to those string resources in the string-array (instead of the text).

To do this,we define the string resources in the /res/strings.xml file like this:

And then we can define a localizable string-array that references the string resources by name in the /res/arrays.xml file like this:

You can also use references to make aliases to other resources. For example, you can alias the system resource for the OK string to an application resource name by including the following in your strings.xml resource file:

You learn more about all the different system resources available later in this chapter.

Working with Layouts

Much as web designers use HTML, user interface designers can use XML to define Android application screen elements and layout. A layout XML resource is where many different resources come together to form the definition of an Android application screen. Layout resource files are included in the /res/layout/ directory and are compiled into the application package at build time. Layout files might include many user interface controls and define the layout for an entire screen or describe custom controls used in other layouts.

Here’s a simple example of a layout file (/res/layout/main.xml) that sets the screen’s back ground color and displays some text in the middle of the screen.

The main.xml layout file that displays this screen references a number of other resources, including colors, strings, and dimension values, all of which were defined in the strings.xml, colors.xml, and dimens.xml resource files.The color resource for the screen background color and resources for a TextView control’s color, string, and text size follows:

main.xml layout file displays in the emulator.

How-the-main_xml-layout-file

The preceding layout describes all the visual elements on a screen. In this example, a LinearLayout control is used as a container for other user interface controls—here, a single TextView that displays a line of text.

Designing Layouts in Eclipse

Layouts can be designed and previewed in Eclipse using the Resource editor functionality provided by the Android plug-in. If you click the project file /res /layout /main.xml (provided with any new Android project), you see a Layout tab, which shows you the preview of the layout, and a main.xml tab, which shows you the raw XML of the layout file.

Designing a layout file using Eclipse.

Designing a layout file using Eclipse.

As with most user interface designers, the Android plug-in works well for your basic layout needs, enables you to create user interface controls such as TextView and Button controls easily, and enables setting the controls’ properties in the Properties pane.

Now is a great time to get to know the layout resource designer. Try creating a new Android project called ParisView (available as a sample project). Navigate to the /res/layout/main.xml layout file and double-click it to open it in the resource editor. It’s quite simple by default, only a black (empty) rectangle and string of text.

Below in the Resource pane of the Eclipse perspective, you notice the Outline tab. This outline is the XML hierarchy of this layout file. By default, you see a LinearLayout.

If you expand it, you see it contains one TextView control. Click on the TextView control. You see that the Properties pane of the Eclipse perspective now has all the properties available for that object. If you scroll down to the property called text, you see that it’s set to a string resource variable @string/hello.

You can use the layout designer to set and preview layout control properties. For example, you can modify the TextView property called text Size by typing 18pt (a dimension). You see the results of your change to the property immediately in the preview area.

Take a moment to switch to the main.xml tab. You notice that the properties you set are now in the XML. If you save and run your project in the emulator now, you see similar results to what you see in the designer preview.

Now go back to the Outline pane. You see a green plus and a red minus button. You can use these buttons to add and remove controls to your layout file. For example, select the LinearLayout from the Outline view, and click the green button to add a control within that container object.

Choose the ImageView object. Now you have a new control in your layout. You can’t actually see it yet because it is not fully defined.

Drag two PNG graphics files (or JPG) into your /res/drawable project directory, naming them flag.png and background.png.Now, browse the properties of your ImageView control, and set the Src property by clicking on the resource browser button labeled [...].You can browse all the Drawable resources in your project and select the flag resource you just added. You can also set this property manually by typing @drawable/flag.

Now, you see that the graphic shows up in your preview. While we’re at it, select the LinearLayout object and set its background property to the background Drawable you added.

If you save the layout file and run the application in the emulator or on the phone, you see results much like you did in the resource designer preview pane.

Using Layout Resources Programmatically

Layouts, whether they are Button or ImageView controls, are all derived from the View class. Here’s how you would retrieve a TextView object named TextView01:

You can also access the underlying XML of a layout resource much as you would any XML file. The following code retrieves the main.xml layout file for XML parsing:

A layout with a LinearLayout, TextView, and ImageView, shown in the Android emulator.

A layout with a LinearLayout, TextView, and ImageView, shown in the Android emulator.

Developers can also define custom layouts with unique attributes. We talk much more about layout files and designing Android user interfaces in Chapter “Designing User Interfaces with Layouts.”

Working with Styles

Android user interface designers can group layout element attributes together in styles. Layout controls are all derived from the View base class, which has many useful attributes. Individual controls, such as Checkbox, Button, and TextView, have specialized attributes associated with their behavior.

Styles are tagged with the <style> tag and should be stored in the /res/values/ directory. Style resources are defined in XML and compiled into the application binary at build time.

Styles cannot be previewed using the Eclipse Resource designer but they are displayed correctly in the emulator and on the device.

Here’s an example of a simple style resource file /res/values/styles.xml containing two styles: one for mandatory form fields, and one for optional form fields on TextView and EditText objects:

Many useful style attributes are colors and dimensions. It would be more appropriate to use references to resources. Here’s the styles.xml file again; this time, the color and text size fields are available in the other resource files colors.xml and dimens.xml:

Now, if you can create a new layout with a couple of TextView and EditText text controls, you can set each control’s style attribute by referencing it as such:

Here we have a form layout called /res/layout/form.xml that does that:

The resulting layout has three fields, each made up of one TextView for the label and one EditText where the user can input text. The mandatory style is applied to the mandatory label and text entry. The other two fields use the optional style. The resulting layout would look something like Figure.

A layout using two styles, one for mandatory fields and another for optional fields.

A layout using two styles, one for mandatory fields and another for optional fields

Using Style Resources Programmatically

Styles are applied to specific layout controls such as TextView and Button objects. Usually, you want to supply the style resource id when you call the control’s constructor. For example, the style named myAppIsStyling would be referred to as R.style.myAppIsStyling.

Working with Themes

Themes are much like styles, but instead of being applied to one layout element at a time, they are applied to all elements of a given activity (which, generally speaking, means one screen).

Themes are defined in exactly the same way as styles. Themes use the <style> tag and should be stored in the /res/values directory. The only difference is that instead of applying that named style to a layout element, you define it as the theme attribute of an activity in the Android Manifest .xml file.



Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Android Topics