Using Resources in Code
Using resources in code is just a matter of knowing the full resource ID
and what type of object your resource has been compiled into. Here is the
syntax for referring to a resource:
R.resource_type.resource_name
or
android.R.resource_type.resource_name
Where resource_type
is the R subclass that holds a specific type
of resource. resource_name
is the name attribute for resources
defined in XML files, or the file name (without the extension) for resources
defined by other file types. Each type of resource will be added to a specific
R subclass, depending on the type of resource it is; to learn which R subclass
hosts your compiled resource type, consult the
Available Resources document. Resources compiled by your own application can
be referred to without a package name (simply as
R.resource_type.resource_name
). Android contains
a number of standard resources, such as screen styles and button backgrounds. To
refer to these in code, you must qualify them with android
, as in
android.R.drawable.button_background
.
Here are some good and bad examples of using compiled resources in code:
// Load a background for the current screen from a drawable resource.
this.getWindow().setBackgroundDrawableResource(R.drawable.my_background_image);
// WRONG Sending a string resource reference into a
// method that expects a string.
this.getWindow().setTitle(R.string.main_title);
// RIGHT Need to get the title from the Resources wrapper.
this.getWindow().setTitle(Resources.getText(R.string.main_title));
// Load a custom layout for the current screen.
setContentView(R.layout.main_screen);
// Set a slide in animation for a ViewFlipper object.
mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
R.anim.hyperspace_in));
// Set the text on a TextView object.
TextView msgTextView = (TextView)findViewByID(R.id.msg);
msgTextView.setText(R.string.hello_message);