Android Tutorial

(avery) #1
Android Tutorial 127

Enough about alternative resources; let’s spend the rest of this
chapter talking about how to create the default resources first. In
Chapter “Targeting Different Device Configurations and
Languages,” we discuss how to use alternative resources to make
your Android applications compatible with many different device
configurations.


Accessing Resources Programmatically


Developers access specific application resources using the R.java
class file and its subclasses, which are automatically generated
when you add resources to your project (if you use Eclipse).You
can refer to any resource identifier in your project by name. For
example, the following string resource named strHello defined
within the resource file called /res /values /strings .xml is accessed
in the code as R.string.strHello


This variable is not the actual data associated with the string
named hello. Instead, you use this resource identifier to retrieve
the resource of that type (which happens to be string).


For example, a simple way to retrieve the string text is to call


String myString = getResources().getString(R.string.strHello);


First, you retrieve the Resources instance for your application
Context (android .content. Context), which is, in this case, this
because the Activity class extends Context.Then you use the
Resources instance to get the appropriate kind of resource you
want. You find that the Resources class

Free download pdf