Color Resources

As you can do with string resources, you can use reference identifiers to indirectly reference colors. Doing this enables Android to localize colors and apply themes. Once you've defined and identified colors in resource files, you can access them in Java code through their IDs. Whereas string-resource IDs are available under the <your-package>.R.string namespace, the color IDs are available under the <your-package>.R.color namespace.

See Listing 3-3 for some examples of specifying color in an XML resource file.

Listing 3-3. XML Syntax for Defining Color Resources

<resources>

<color name="red">#f00</color> <color name="blue">#0000ff</color> <color name="green">#f0f0</color>

<color name="main_back_ground_color">#ffffff00</color> </resources>

The entries in Listing 3-3 need to be in a file residing in the /res/values subdirectory. The name of the file is arbitrary, meaning the file name can be anything you choose. Listing 3-4 shows an example of using a color resource in Java code.

Listing 3-4. Color Resources in Java code int mainBackGroundColor

= activity.getResources.getColor(R.color.main_back_ground_color);

Listing 3-5 shows how you would use a color resource in a view definition.

Listing 3-5. Using Colors in View Definitions

<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="@color/ red"

android:text="Sample Text to Show Red Color"/>

0 0

Post a comment