News:
- In an internet driven environment, it is imperative for a company to keep its product or business to the forefront of potential customers' minds. The ...
- A successful enterprise is all about constantly reinventing ways to work more efficiently. In today’s techno age, this translates to testing new too...
- The IT industry plays a pivotal role in providing application development solutions and custom software development to a wide range of industries, i...
- Royal Victorian Eye and Ear Hospital, 2010 Atcomm has been contracted to implement a complex IOP glaucoma management tool which will be distribut...
- We are pleased to announce another implementation of a CMS system for a large Melbourne based fitness center - Star Plate Studio. Atcomm has depl...
Thursday, 29 July 2010 00:03
Using resources, Content Providers, and Intents
-
font size
decrease font size
increase font size
In Chapter 2, you got an overview of an Android application and a quick look at some of its underlying concepts. Among these, resources, content providers, and intents form the three primary pillars of Android UI programming. Android depends on resources for look-and-feel flexibility, content providers for abstracting data into services, and intents for interoperability
and UI reuse. You must fully understand these three concepts in order to build successful Android applications, so we’ll discuss them in depth here.
Understanding Resources
Resources are critical to the Android architecture. In this section, you’ll learn what resources are and how to create them using resource files. You’ll find out that resources are declarative, and that Android creates resource IDs for convenient use in your Java programs. You’ll also see how the R.java source file mediates the generation and usage of these resource IDs. Then
you’ll learn how to define resources in XML files, reuse resources in other resource XML definitions, and reuse resources in Java programs. In addition to these XML-based resources, this chapter also covers two other types of resources: raw resources and assets.
String Resources
A resource in Android is a file (like a music file) or a value (like the title of a dialog box) that is bound to an executable application. These files and values are bound to the executable in such a way that you can change them without recompiling and redeploying the application.
Resources play a part in many, if not all, familiar UI frameworks. Familiar examples of resources include strings, colors, and bitmaps. Instead of hard-coding strings in an application, for example, you can use their IDs instead. This indirection lets you change the text of the string resource without changing the source code.
Let’s start with strings and see how they are used as resources. Android allows you to define multiple strings in one or more XML resource files. These XML files containing string-resource definitions reside in the /res/values subdirectory. The names of the XML files are arbitrary, although you will commonly see the file name as strings.xml. Listing 3-1 shows an example of
a string-resource file.
Listing 3-1. Example strings.xml File
hello
hello appname
When this file is created or updated, the Eclipse ADT plug-in will automatically update a Java class in your application’s root package called R.java with unique IDs for the two string resources specified.
For the string-resource file in Listing 3-1, the updated R.java file would have these entries:
public final class R {
...other entries depending on your project and application
public static final class string
{
...other entries depending on your project and application
public static final int hello=0x7f040000;
public static final int app_name=0x7f040001;
...other entries depending on your project and application
}
...other entries depending on your project and application
}
Let’s focus on the static definition for static final class string. R.java creates this inner static class as a namespace to hold string-resource IDs. The two static final ints defined with variable names hello and app_name are the resource IDs that represent the corresponding string resources. You could use these resource IDs anywhere in the source code through the following code structure:
R.string.hello
Note that these generated IDs point to ints rather than strings. Most methods that take strings also take these resource identifiers as inputs. Android will resolve those ints to strings where needed.
It is merely a convention that most sample applications define all strings in one strings. xml file. Android takes any number of arbitrary files as long as the structure of the XML file looks like Listing 3-1 and the file resides in the /res/values subdirectory.
The structure of this file is easy to follow. You have the root node of followed by one or more of its child elements of . Each element or node has a property called name that will end up as the id attribute in R.java and the actual text for that string ID.
To see that multiple string-resource files are allowed in this subdirectory, you can place another file with the following content in the same subdirectory and call it strings1.xml:
hello 1
hello appname 1
The Eclipse ADT plug-in will validate the uniqueness of these IDs at compile time and place them in R.java as two additional constants: R.string.hello1 and R.string.app_name1.
Layout Resources
A layout resource is another key resource commonly used in Android programming. In Android, the view for a screen is often loaded from an XML file as a resource. These XML files are called layout resources. Consider this code segment for a sample Android activity:
public class HelloWorldActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView)this.findViewById(R.id.text1);
tv.setText("Try this text instead");
}
………
}
The line setContentView(R.layout.main) points out that there is a static class called R.layout, and within that class there is a constant called main (an integer) pointing to a View defined by an XML layout-resource file. The name of the XML file would be main.xml, which needs to be placed in the resources’ layout subdirectory. In other words, this statement would expect the programmer to create the file /res/layout/main.xml and place the necessary layout definition in that file. The contents of the main.xml layout file could look like Listing 3-2.
Listing 3-2. Example main.xml Layout File
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@+string/hello"
/>
The layout file in Listing 3-2 defines a root node called LinearLayout, which contains a TextView followed by a Button. A LinearLayout lays out its children vertically or horizontally— vertically, in this example.
You will need to define a separate layout file for each screen. More accurately, each layout needs a dedicated file. If you are painting two screens, you will likely need two layout files such as /res/layout/screen1_layout.xml and /res/layout/screen2_layout.xml.
For example, if you have two files under /res/layout/ called file1.xml and file2.xml, you’ll have the following entries in R.java:
public static final class layout {
.... any other files
public static final int file1=0x7f030000;
public static final int file2=0x7f030001;
}
The views defined in these layout files are accessible in code if you reference their IDs from R.java:
TextView tv = (TextView)this.findViewById(R.id.text1);
tv.setText("Try this text instead");
In this example, you locate the TextView by using the findViewById method of the Activity class. The constant R.id.text1 corresponds to the ID defined for the TextView. The id for the TextView in the layout file is as follows:
..
The attribute value for the id attribute indicates that a constant called text1 will be used to uniquely identify this view among other views hosted by that activity. The plus sign (+) in @+id/text1 means that text1 will be created if it doesn’t exist already. There is more to this syntax, in which ids are assigned to resources. We’ll talk about that next.
Resource-Reference Syntax
Irrespective of the type of resource, all Android resources are identified (or referenced) by their id in Java source code. The syntax you use to allocate an id to a resource in the XML file is called resource-reference syntax. The id attribute syntax in the previous example @+id/text1 has the following formal structure:
@[package:]type/name
The type corresponds to one of the resource-type namespaces available in R.java, such as
the following:
• R.drawable
• R.id
• R.layout
• R.string
• R.attr
The corresponding types in XML resource-reference syntax are as follows:
• drawable
• id
• layout
• string
• attr
The name part in the resource reference @[package:]type/name is the name given to the resource; it also gets represented as an int constant in R.java. Now we have come to the important part of this syntax: the package. If you don’t specify any package, then the pair type/ name will be resolved based on local resources and the application’s local R.java package.
If you specify android:type/name, on the other hand, the reference will look in the package identified by android: the android.R.java file, to be precise. So you can use any Java package name in place of the package placeholder to locate the right R.java file to resolve the reference. Based on this information, let’s analyze a few examples:
// Compile error, as id will not take raw text strings
// wrong syntax. It is missing a type name
// you will get an error "No Resource type specified
//Error: No Resource found that matches id "text"
//Unless you have taken care to define "text" before
// Error: Resource is not public
// indicating that there is no such id in android.R.id
// Of course this would be valid if Android R.java were to define
// an id with this name
//Success: Creates an id called "text" in the local package
Defining Your Own Resource IDs for Later Use
The general pattern for allocating an id is either to create a new one or to use the one created by the Android package. However, it is possible to create ids beforehand and use them later in your own packages.
The line in the preceding code segment indicates that an id named text is going to be used if one already exists. If the id doesn’t exist, then a new one is going to be created. So when might an id such as text already exist in R.java for it to be reused?
You might be inclined to put a constant like R.id.text in R.java, but R.java is not editable. Even if it were, it gets regenerated every time something gets changed, added, or deleted in the /res/* subdirectory. However, you can use a resource tag called item to define an id without attaching to any particular resource. Here is an example:
The type refers to the type of resource—an id in this case. Once this id is in place, the following
View definition would work:
..
and UI reuse. You must fully understand these three concepts in order to build successful Android applications, so we’ll discuss them in depth here.
Understanding Resources
Resources are critical to the Android architecture. In this section, you’ll learn what resources are and how to create them using resource files. You’ll find out that resources are declarative, and that Android creates resource IDs for convenient use in your Java programs. You’ll also see how the R.java source file mediates the generation and usage of these resource IDs. Then
you’ll learn how to define resources in XML files, reuse resources in other resource XML definitions, and reuse resources in Java programs. In addition to these XML-based resources, this chapter also covers two other types of resources: raw resources and assets.
String Resources
A resource in Android is a file (like a music file) or a value (like the title of a dialog box) that is bound to an executable application. These files and values are bound to the executable in such a way that you can change them without recompiling and redeploying the application.
Resources play a part in many, if not all, familiar UI frameworks. Familiar examples of resources include strings, colors, and bitmaps. Instead of hard-coding strings in an application, for example, you can use their IDs instead. This indirection lets you change the text of the string resource without changing the source code.
Let’s start with strings and see how they are used as resources. Android allows you to define multiple strings in one or more XML resource files. These XML files containing string-resource definitions reside in the /res/values subdirectory. The names of the XML files are arbitrary, although you will commonly see the file name as strings.xml. Listing 3-1 shows an example of
a string-resource file.
Listing 3-1. Example strings.xml File
When this file is created or updated, the Eclipse ADT plug-in will automatically update a Java class in your application’s root package called R.java with unique IDs for the two string resources specified.
For the string-resource file in Listing 3-1, the updated R.java file would have these entries:
public final class R {
...other entries depending on your project and application
public static final class string
{
...other entries depending on your project and application
public static final int hello=0x7f040000;
public static final int app_name=0x7f040001;
...other entries depending on your project and application
}
...other entries depending on your project and application
}
Let’s focus on the static definition for static final class string. R.java creates this inner static class as a namespace to hold string-resource IDs. The two static final ints defined with variable names hello and app_name are the resource IDs that represent the corresponding string resources. You could use these resource IDs anywhere in the source code through the following code structure:
R.string.hello
Note that these generated IDs point to ints rather than strings. Most methods that take strings also take these resource identifiers as inputs. Android will resolve those ints to strings where needed.
It is merely a convention that most sample applications define all strings in one strings. xml file. Android takes any number of arbitrary files as long as the structure of the XML file looks like Listing 3-1 and the file resides in the /res/values subdirectory.
The structure of this file is easy to follow. You have the root node of
To see that multiple string-resource files are allowed in this subdirectory, you can place another file with the following content in the same subdirectory and call it strings1.xml:
The Eclipse ADT plug-in will validate the uniqueness of these IDs at compile time and place them in R.java as two additional constants: R.string.hello1 and R.string.app_name1.
Layout Resources
A layout resource is another key resource commonly used in Android programming. In Android, the view for a screen is often loaded from an XML file as a resource. These XML files are called layout resources. Consider this code segment for a sample Android activity:
public class HelloWorldActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView)this.findViewById(R.id.text1);
tv.setText("Try this text instead");
}
………
}
The line setContentView(R.layout.main) points out that there is a static class called R.layout, and within that class there is a constant called main (an integer) pointing to a View defined by an XML layout-resource file. The name of the XML file would be main.xml, which needs to be placed in the resources’ layout subdirectory. In other words, this statement would expect the programmer to create the file /res/layout/main.xml and place the necessary layout definition in that file. The contents of the main.xml layout file could look like Listing 3-2.
Listing 3-2. Example main.xml Layout File
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_height="wrap_content"
android:text="@string/hello"
/>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@+string/hello"
/>
The layout file in Listing 3-2 defines a root node called LinearLayout, which contains a TextView followed by a Button. A LinearLayout lays out its children vertically or horizontally— vertically, in this example.
You will need to define a separate layout file for each screen. More accurately, each layout needs a dedicated file. If you are painting two screens, you will likely need two layout files such as /res/layout/screen1_layout.xml and /res/layout/screen2_layout.xml.
For example, if you have two files under /res/layout/ called file1.xml and file2.xml, you’ll have the following entries in R.java:
public static final class layout {
.... any other files
public static final int file1=0x7f030000;
public static final int file2=0x7f030001;
}
The views defined in these layout files are accessible in code if you reference their IDs from R.java:
TextView tv = (TextView)this.findViewById(R.id.text1);
tv.setText("Try this text instead");
In this example, you locate the TextView by using the findViewById method of the Activity class. The constant R.id.text1 corresponds to the ID defined for the TextView. The id for the TextView in the layout file is as follows:
The attribute value for the id attribute indicates that a constant called text1 will be used to uniquely identify this view among other views hosted by that activity. The plus sign (+) in @+id/text1 means that text1 will be created if it doesn’t exist already. There is more to this syntax, in which ids are assigned to resources. We’ll talk about that next.
Resource-Reference Syntax
Irrespective of the type of resource, all Android resources are identified (or referenced) by their id in Java source code. The syntax you use to allocate an id to a resource in the XML file is called resource-reference syntax. The id attribute syntax in the previous example @+id/text1 has the following formal structure:
@[package:]type/name
The type corresponds to one of the resource-type namespaces available in R.java, such as
the following:
• R.drawable
• R.id
• R.layout
• R.string
• R.attr
The corresponding types in XML resource-reference syntax are as follows:
• drawable
• id
• layout
• string
• attr
The name part in the resource reference @[package:]type/name is the name given to the resource; it also gets represented as an int constant in R.java. Now we have come to the important part of this syntax: the package. If you don’t specify any package, then the pair type/ name will be resolved based on local resources and the application’s local R.java package.
If you specify android:type/name, on the other hand, the reference will look in the package identified by android: the android.R.java file, to be precise. So you can use any Java package name in place of the package placeholder to locate the right R.java file to resolve the reference. Based on this information, let’s analyze a few examples:
// Compile error, as id will not take raw text strings
// wrong syntax. It is missing a type name
// you will get an error "No Resource type specified
//Error: No Resource found that matches id "text"
//Unless you have taken care to define "text" before
// Error: Resource is not public
// indicating that there is no such id in android.R.id
// Of course this would be valid if Android R.java were to define
// an id with this name
//Success: Creates an id called "text" in the local package
Defining Your Own Resource IDs for Later Use
The general pattern for allocating an id is either to create a new one or to use the one created by the Android package. However, it is possible to create ids beforehand and use them later in your own packages.
The line
You might be inclined to put a constant like R.id.text in R.java, but R.java is not editable. Even if it were, it gets regenerated every time something gets changed, added, or deleted in the /res/* subdirectory. However, you can use a resource tag called item to define an id without attaching to any particular resource. Here is an example:
The type refers to the type of resource—an id in this case. Once this id is in place, the following
View definition would work:
..
Read 30 times
Published in
Java
John
Latest from John
More in this category:
« Examining the Application Lifecycle
Compiled and Noncompiled Android Resources »