References to Resources

A value supplied in an attribute (or resource) can also be a reference to a resource. This is often used in layout files to supply strings (so they can be localized) and images (which exist in another file), though a reference can be any resource type including colors and integers.

For example, if we have color resources, we can write a layout file that sets the text color size to be the value contained in one of those resources:

<?xml version="1.0" encoding="utf-8"?> <EditText id="text"

xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:textColor="@color/opaque_red" android:text="Hello, World!" />

Note here the use of the '@' prefix to introduce a resource reference -- the text following that is the name of a resource in the form of @[package:]type/name. In this case we didn't need to specify the package because we are referencing a resource in our own package. To reference a system resource, you would need to write:

<?xml version="1.0" encoding="utf-8"?> <EditText id="text"

xmlns:android="http://schemas.android.com/apk/res/android" android:layout width="fill parent" android:layout height="fill parent" android:textColor="@android:color/opaque red" android:text="Hello, World!" />

As another example, you should always use resource references when supplying strings in a layout file so that they can be localized:

<?xml version="1.0" encoding="utf-8"?> <EditText id="text"

xmlns:android="http://schemas.android.com/apk/res/android" android:layout width="fill parent" android:layout height="fill parent" android:textColor="@android:color/opaque red" android:text="@string/hello world" />

This facility can also be used to create references between resources. For example, we can create new drawable resources that are aliases for existing images:

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

<drawable id="my background">@android:drawable/theme2 background</drawable> </resources>

0 0

Post a comment