Use of System Resources in Android

The Android framework makes many native resources available, providing you with various strings, images, animations, styles, and layouts to use in your applications.

Accessing the system resources in code is similar to using your own resources. The difference is that you use the native Android resource classes available from android.R, rather than the applicationspecifi c R class. The following code snippet uses the getString method available in the application context to retrieve an error message available from the system resources:

CharSequence httpError = getString(android.R.string.httpErrorBadUrl);

To access system resources in XML, specify android as the package name, as shown in this XML snippet:

<EditText
 android:id=”@+id/myEditText”
 android:layout_width=”match_parent”
 android:layout_height=”wrap_content”
 android:text=”@android:string/httpErrorBadUrl”
 android:textColor=”@android:color/darker_gray”
/>

Referring to Styles in the Current Theme

Using themes is an excellent way to ensure consistency for your application’s UI. Rather than fully define each style, Android provides a shortcut to enable you to use styles from the currently applied theme.

To do this, use ?android: rather than @ as a prefix to the resource you want to use. The following example shows a snippet of the preceding code but uses the current theme’s text color rather than a system resource:

<EditText
 android:id=”@+id/myEditText”
android:layout_width=”match_parent”
 android:layout_height=”wrap_content”
 android:text=”@android:string/httpErrorBadUrl”
 android:textColor=”?android:textColor”
/>

This technique enables you to create styles that change if the current theme changes, without you modifying each individual style resource.

Leave a Comment