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 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);

0 0

Post a comment