Using Styled Text as a Format String

Sometimes you may want to create a styled text resource that is also used as a format string. This cannot be done directly because there is no way of passing the styled text as the format string argument of String.format() without stripping out the style information. The workaround is to store the style tags as escaped HTML tags, and then convert the escaped HTML string into a styled text after formatting has taken place.

To use styled text as a format string, do the following.

1. Store your styled text resource as an escaped string, so that the HTML tags in your text resource are not interpreted as if they were XML tags:

Millimeters - based on the physical size of the screen.

Points - 1/72 of an inch based on the physical size of the screen.

Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".

Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user's preference.

Dimension values are not normally used as raw resources, but rather as attribute values in XML files. You can, however, create plain resources containing this data type.

Source file format: XML file requiring a <?xml version="1.0" encoding="utf-8"?> declaration, and a root <resources> element containing one or more <dimen> tags.

Resource source file location: res/values/dimens.xml (File name is arbitrary, but standard practice is to put all dimensions in one file devoted to dimensions.)

Compiled resource datatype: Resource pointer to a dimension. Resource reference name:

• XML: @[paciage:]dimen/some name (where some_name is the name of a specific <dimen> element) Syntax

<dimen name=dimen name>dimen value</dimen>

A valid dimension value.

• name - The name used in referring to this dimension. Example XML Declaration

The following code declares several dimension values.


<dimen name="one pixel">1px</dimen> <dimen name="double density">2dp</dimen> <dimen name="sixteen sp">16sp</dimen> </resources>

Example Code Use Example Java code:

0 0

Post a comment