Saturday, February 19, 2011

Reference Android Resource

There are two way to refer a Android resource - from code and from xml resource file.

To refer resource in code, the format is R.Calss.ResourceName. The following are some usage sample.
setcontentview(R.layout.main)

Resources myResources = getResources();
CharSequence styledText = myResources.getText(R.string.stop_message);

To refer resource as attribute in xml, the format is
"@[packagename:]Class/ResourceName" as showing in the following example:



android:text="@string/stop_message" android:textColor="@color/opaque_blue" />


Usually, you do not need to include the package name, unless you need to refer a system defined resource. The following sample referrs to system color darker_gray
android:textColor="@android:color/darker_gray" />

In rare occasion, you may also see a ? in the format as following sample
android:textColor="?android:textColor"

? means using the current textColor defined for the view, so the actual color can only be decided at runtime.

Jonathan

No comments:

Post a Comment