android programming
package com.paad.helloworld;
import android.app.Activity;
import android.os.Bundle;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
}
}
package com.paad.helloworld;
import android.app.Activity;
import android.os.Bundle;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
}
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
}
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Hello World, HelloWorld”
/>
</LinearLayout>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Hello World, HelloWorld”
/>
</LinearLayout>
<TextView
android:id=”@+id/myTextView”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Hello World, HelloWorld”
/>
android:id=”@+id/myTextView”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Hello World, HelloWorld”
/>
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout.LayoutParams lp;lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
LinearLayout.LayoutParams textViewLP;
textViewLP = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
TextView myTextView = new TextView(this);
myTextView.setText(“Hello World, HelloWorld”);
ll.addView(myTextView, textViewLP);
this.addContentView(ll, lp);
}
super.onCreate(icicle);
LinearLayout.LayoutParams lp;lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
LinearLayout.LayoutParams textViewLP;
textViewLP = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
TextView myTextView = new TextView(this);
myTextView.setText(“Hello World, HelloWorld”);
ll.addView(myTextView, textViewLP);
this.addContentView(ll, lp);
}
1. Start by creating a new Android project. Within Eclipse, select File ➪ New ➪ Project …, then
choose Android (as shown in Figure 2-9) before clicking Next.2. In the dialog box that appears (shown in Figure 2-10), enter the details for your new project.
The “Application name” is the friendly name of your application, and the “Activity name” is the
name of your Activity subclass. With the details entered, click Finish to create your new project.
3. Take this opportunity to set up debug and run confi gurations by selecting Run ➪ Open Debug
Dialog … and then Run ➪ Open Run Dialog …, creating a new confi guration for each, specifying
the Todo_List project. You can leave the launch actions as Launch Default Activity or
explicitly set them to launch the new ToDoList4. Now decide what you want to show the users and what actions they’ll need to perform. Design
a user interface that will make this as intuitive as possible.
In this example, we want to present users with a list of to-do items and a text entry box to add new
ones. There’s both a list and a text entry control (View) available from the Android libraries. You’ll learn
more about the Views available in Android and how to create new ones in Chapter 4.
The preferred method for laying out your UI is using a layout resource fi le. Open the main.xml layout
fi le in the res/layout project folder
5. Modify the main layout to include a ListView and an EditText within a LinearLayout. It’s
important to give both the EditText and ListView controls IDs so you can get references to
them in code.
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>
<EditText
android:id=”@+id/myEditText”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”New To Do Item”
/>
<ListView
android:id=”@+id/myListView”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
/>
</LinearLayout>
6. With your user interface defi ned, open the ToDoList.java Activity class from your project’s
source folder. In this example, you’ll make all your changes by overriding the onCreate
method. Start by infl ating your UI using setContentView and then get references to the
ListView and EditText using findViewById.
public void onCreate(Bundle icicle) {
// Inflate your view
setContentView(R.layout.main);
// Get references to UI widgets
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
}
7. Still within onCreate, defi ne an ArrayList of Strings to store each to-do list item. You can
bind a ListView to an ArrayList using an ArrayAdapter, so create a new ArrayAdapter
instance to bind the to-do item array to the ListView. We’ll return to ArrayAdapters in
Chapter 5.
public void onCreate(Bundle icicle) {
setContentView(R.layout.main);
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
// Create the array list of to do items
final ArrayList<String> todoItems = new ArrayList<String>();
// Create the array adapter to bind the array to the listview
final ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
todoItems);
// Bind the array adapter to the listview.
myListView.setAdapter(aa);
}
8. The fi nal step to make this to-do list functional is to let users add new to-do items. Add an
onKeyListener to the EditText that listens for a “D-pad center button” click before adding
the contents of the EditText to the to-do list array and notifying the ArrayAdapter of the
change. Then clear the EditText to prepare for another item.
public void onCreate(Bundle icicle) {
setContentView(R.layout.main);
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
final ArrayList<String> todoItems = new ArrayList<String>();
final ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
todoItems);
myListView.setAdapter(aa);
myEditText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
todoItems.add(0, myEditText.getText().toString());
aa.notifyDataSetChanged();
myEditText.setText(“”);
return true;
}
return false;
}
});
}
9. Run or debug the application, and you’ll see a text entry box above a list
10. You’ve now fi nished your fi rst “real” Android application. Try adding breakpoints to the code
to test the debugger and experiment with the DDMS perspective.
As it stands, this to-do list application isn’t spectacularly useful. It doesn’t save to-do list items between
sessions, you can’t edit or remove an item from the list, and typical task list items like due dates and
task priority aren’t recorded or displayed. On balance, it fails most of the criteria laid out so far for a
good mobile application design.
You’ll rectify some of these defi ciencies when you return to this example in later chapters.
choose Android (as shown in Figure 2-9) before clicking Next.2. In the dialog box that appears (shown in Figure 2-10), enter the details for your new project.
The “Application name” is the friendly name of your application, and the “Activity name” is the
name of your Activity subclass. With the details entered, click Finish to create your new project.
3. Take this opportunity to set up debug and run confi gurations by selecting Run ➪ Open Debug
Dialog … and then Run ➪ Open Run Dialog …, creating a new confi guration for each, specifying
the Todo_List project. You can leave the launch actions as Launch Default Activity or
explicitly set them to launch the new ToDoList4. Now decide what you want to show the users and what actions they’ll need to perform. Design
a user interface that will make this as intuitive as possible.
In this example, we want to present users with a list of to-do items and a text entry box to add new
ones. There’s both a list and a text entry control (View) available from the Android libraries. You’ll learn
more about the Views available in Android and how to create new ones in Chapter 4.
The preferred method for laying out your UI is using a layout resource fi le. Open the main.xml layout
fi le in the res/layout project folder
5. Modify the main layout to include a ListView and an EditText within a LinearLayout. It’s
important to give both the EditText and ListView controls IDs so you can get references to
them in code.
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>
<EditText
android:id=”@+id/myEditText”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”New To Do Item”
/>
<ListView
android:id=”@+id/myListView”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
/>
</LinearLayout>
6. With your user interface defi ned, open the ToDoList.java Activity class from your project’s
source folder. In this example, you’ll make all your changes by overriding the onCreate
method. Start by infl ating your UI using setContentView and then get references to the
ListView and EditText using findViewById.
public void onCreate(Bundle icicle) {
// Inflate your view
setContentView(R.layout.main);
// Get references to UI widgets
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
}
7. Still within onCreate, defi ne an ArrayList of Strings to store each to-do list item. You can
bind a ListView to an ArrayList using an ArrayAdapter, so create a new ArrayAdapter
instance to bind the to-do item array to the ListView. We’ll return to ArrayAdapters in
Chapter 5.
public void onCreate(Bundle icicle) {
setContentView(R.layout.main);
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
// Create the array list of to do items
final ArrayList<String> todoItems = new ArrayList<String>();
// Create the array adapter to bind the array to the listview
final ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
todoItems);
// Bind the array adapter to the listview.
myListView.setAdapter(aa);
}
8. The fi nal step to make this to-do list functional is to let users add new to-do items. Add an
onKeyListener to the EditText that listens for a “D-pad center button” click before adding
the contents of the EditText to the to-do list array and notifying the ArrayAdapter of the
change. Then clear the EditText to prepare for another item.
public void onCreate(Bundle icicle) {
setContentView(R.layout.main);
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
final ArrayList<String> todoItems = new ArrayList<String>();
final ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
todoItems);
myListView.setAdapter(aa);
myEditText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
todoItems.add(0, myEditText.getText().toString());
aa.notifyDataSetChanged();
myEditText.setText(“”);
return true;
}
return false;
}
});
}
9. Run or debug the application, and you’ll see a text entry box above a list
10. You’ve now fi nished your fi rst “real” Android application. Try adding breakpoints to the code
to test the debugger and experiment with the DDMS perspective.
As it stands, this to-do list application isn’t spectacularly useful. It doesn’t save to-do list items between
sessions, you can’t edit or remove an item from the list, and typical task list items like due dates and
task priority aren’t recorded or displayed. On balance, it fails most of the criteria laid out so far for a
good mobile application design.
You’ll rectify some of these defi ciencies when you return to this example in later chapters.
Introducing the Application Manifest
Each Android project includes a manifest fi le, AndroidManifest.xml, stored in the root of the project
hierarchy. The manifest lets you defi ne the structure and metadata of your application and its
components.It includes nodes for each of the components (Activities, Services, Content Providers, and Broadcast
Receivers) that make up your application and, using Intent Filters and Permissions, determines how
they interact with each other and other applications.
It also offers attributes to specify application metadata (like its icon or theme), and additional top-level
nodes can be used for security settings and unit tests as described below.
The manifest is made up of a root manifest tag with a package attribute set to the project’s package.
It usually includes an xmlns:android attribute that supplies several system attributes used within the
fi le. A typical manifest node is shown in the XML snippet below:
<manifest xmlns:android=http://schemas.android.com/apk/res/android
package=”com.my_domain.my_app”>
[ ... manifest nodes ... ]
</manifest>
The manifest tag includes nodes that defi ne the application components, security settings, and test
classes that make up your application. The following list gives a summary of the available manifest
node tags, and an XML snippet demonstrating how each one is used:
❑ application A manifest can contain only one application node. It uses attributes to specify
the metadata for your application (including its title, icon, and theme). It also acts as a container
that includes the Activity, Service, Content Provider, and Broadcast Receiver tags used to specify
the application components.
<application android:icon=”@drawable/icon”
android:theme=”@style/my_theme”>
[ ... application nodes ... ]
</application>
❑ activity An activity tag is required for every Activity displayed by your application,
using the android:name attribute to specify the class name. This must include the
main launch Activity and any other screen or dialogs that can be displayed. Trying to
start an Activity that’s not defi ned in the manifest will throw a runtime exception. Each
Activity node supports intent-filter child tags that specify which Intents launch the
Activity.
<activity android:name=”.MyActivity” android:label=”@string/app_name”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
❑ service As with the activity tag, create a new service tag for each Service class
used in your application. (Services are covered in detail in Chapter 8.) Service tags also
support intent-filter child tags to allow late runtime binding.
<service android:enabled=”true” android:name=”.MyService”></service>
❑ provider Provider tags are used for each of your application’s Content Providers.
Content Providers are used to manage database access and sharing within and between
applications and are examined in Chapter 6.
<provider android:permission=”com.paad.MY_PERMISSION”
android:name=”.MyContentProvider”
android:enabled=”true”
android:authorities=”com.paad.myapp.MyContentProvider”>
</provider>
❑ receiver By adding a receiver tag, you can register a Broadcast Receiver without
having to launch your application fi rst. As you’ll see in Chapter 5, Broadcast Receivers
are like global event listeners that, once registered, will execute whenever a matching
Intent is broadcast by an application. By registering a Broadcast Receiver in the manifest,
you can make this process entirely autonomous. If a matching Intent is broadcast,
your application will be started automatically and the registered Broadcast Receiver
will be run.
<receiver android:enabled=”true”
android:label=”My Broadcast Receiver”
android:name=”.MyBroadcastReceiver”>
</receiver>
❑ uses-permission As part of the security model, uses-permission tags declare the permissions
you’ve determined that your application needs for it to operate properly. The permissions
you include will be presented to the user, to grant or deny, during installation. Permissions
are required for many of the native Android services, particularly those with a cost or security
implication (such as dialing, receiving SMS, or using the location-based services). As shown
in the item below, third-party applications, including your own, can also specify permissions
before providing access to shared application components.
<uses-permission android:name=”android.permission.ACCESS_LOCATION”>
</uses-permission>
❑ permission Before you can restrict access to an application component, you need to defi ne
a permission in the manifest. Use the permission tag to create these permission defi nitions.
Application components can then require them by adding the android:permission attribute.
Other applications will then need to include a uses-permission tag in their manifests (and
have it granted) before they can use these protected components.
Within the permission tag, you can specify the level of access the permission will permit
(normal, dangerous, signature, signatureOrSystem), a label, and an external resource
containing the description that explain the risks of granting this permission.
<permission android:name=”com.paad.DETONATE_DEVICE”
android:protectionLevel=”dangerous”
android:label=”Self Destruct”
android:description=”@string/detonate_description”>
</permission>❑ instrumentation Instrumentation classes provide a framework for running tests on your
Activities and Services at run time. They provide hooks to monitor your application and its
interaction with the system resources. Create a new node for each of the test classes you’ve created
for your application.
<instrumentation android:label=”My Test”
android:name=”.MyTestClass”
android:targetPackage=”com.paad.aPackage”>
</instrumentation>
A more detailed description of the manifest and each of these nodes can be found at
http://code.google.com/android/devel/bblocks-manifest.html
The ADT New Project Wizard automatically creates a new manifest fi le when it creates a new project.
You’ll return to the manifest as each of the application components is introduced.
Each Android project includes a manifest fi le, AndroidManifest.xml, stored in the root of the project
hierarchy. The manifest lets you defi ne the structure and metadata of your application and its
components.It includes nodes for each of the components (Activities, Services, Content Providers, and Broadcast
Receivers) that make up your application and, using Intent Filters and Permissions, determines how
they interact with each other and other applications.
It also offers attributes to specify application metadata (like its icon or theme), and additional top-level
nodes can be used for security settings and unit tests as described below.
The manifest is made up of a root manifest tag with a package attribute set to the project’s package.
It usually includes an xmlns:android attribute that supplies several system attributes used within the
fi le. A typical manifest node is shown in the XML snippet below:
<manifest xmlns:android=http://schemas.android.com/apk/res/android
package=”com.my_domain.my_app”>
[ ... manifest nodes ... ]
</manifest>
The manifest tag includes nodes that defi ne the application components, security settings, and test
classes that make up your application. The following list gives a summary of the available manifest
node tags, and an XML snippet demonstrating how each one is used:
❑ application A manifest can contain only one application node. It uses attributes to specify
the metadata for your application (including its title, icon, and theme). It also acts as a container
that includes the Activity, Service, Content Provider, and Broadcast Receiver tags used to specify
the application components.
<application android:icon=”@drawable/icon”
android:theme=”@style/my_theme”>
[ ... application nodes ... ]
</application>
❑ activity An activity tag is required for every Activity displayed by your application,
using the android:name attribute to specify the class name. This must include the
main launch Activity and any other screen or dialogs that can be displayed. Trying to
start an Activity that’s not defi ned in the manifest will throw a runtime exception. Each
Activity node supports intent-filter child tags that specify which Intents launch the
Activity.
<activity android:name=”.MyActivity” android:label=”@string/app_name”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
❑ service As with the activity tag, create a new service tag for each Service class
used in your application. (Services are covered in detail in Chapter 8.) Service tags also
support intent-filter child tags to allow late runtime binding.
<service android:enabled=”true” android:name=”.MyService”></service>
❑ provider Provider tags are used for each of your application’s Content Providers.
Content Providers are used to manage database access and sharing within and between
applications and are examined in Chapter 6.
<provider android:permission=”com.paad.MY_PERMISSION”
android:name=”.MyContentProvider”
android:enabled=”true”
android:authorities=”com.paad.myapp.MyContentProvider”>
</provider>
❑ receiver By adding a receiver tag, you can register a Broadcast Receiver without
having to launch your application fi rst. As you’ll see in Chapter 5, Broadcast Receivers
are like global event listeners that, once registered, will execute whenever a matching
Intent is broadcast by an application. By registering a Broadcast Receiver in the manifest,
you can make this process entirely autonomous. If a matching Intent is broadcast,
your application will be started automatically and the registered Broadcast Receiver
will be run.
<receiver android:enabled=”true”
android:label=”My Broadcast Receiver”
android:name=”.MyBroadcastReceiver”>
</receiver>
❑ uses-permission As part of the security model, uses-permission tags declare the permissions
you’ve determined that your application needs for it to operate properly. The permissions
you include will be presented to the user, to grant or deny, during installation. Permissions
are required for many of the native Android services, particularly those with a cost or security
implication (such as dialing, receiving SMS, or using the location-based services). As shown
in the item below, third-party applications, including your own, can also specify permissions
before providing access to shared application components.
<uses-permission android:name=”android.permission.ACCESS_LOCATION”>
</uses-permission>
❑ permission Before you can restrict access to an application component, you need to defi ne
a permission in the manifest. Use the permission tag to create these permission defi nitions.
Application components can then require them by adding the android:permission attribute.
Other applications will then need to include a uses-permission tag in their manifests (and
have it granted) before they can use these protected components.
Within the permission tag, you can specify the level of access the permission will permit
(normal, dangerous, signature, signatureOrSystem), a label, and an external resource
containing the description that explain the risks of granting this permission.
<permission android:name=”com.paad.DETONATE_DEVICE”
android:protectionLevel=”dangerous”
android:label=”Self Destruct”
android:description=”@string/detonate_description”>
</permission>❑ instrumentation Instrumentation classes provide a framework for running tests on your
Activities and Services at run time. They provide hooks to monitor your application and its
interaction with the system resources. Create a new node for each of the test classes you’ve created
for your application.
<instrumentation android:label=”My Test”
android:name=”.MyTestClass”
android:targetPackage=”com.paad.aPackage”>
</instrumentation>
A more detailed description of the manifest and each of these nodes can be found at
http://code.google.com/android/devel/bblocks-manifest.html
The ADT New Project Wizard automatically creates a new manifest fi le when it creates a new project.
You’ll return to the manifest as each of the application components is introduced.
Creating Simple Values
Supported simple values include strings, colors, dimensions, and string or integer arrays. All simple
values are stored within XML fi les in the res/values folder.
Within each XML fi le, you indicate the type of value being stored using tags as shown in the sample
XML fi le below:
<?xml version=”1.0” encoding=”utf-8”?>
<resources>
<string name=”app_name”>To Do List</string>
<color name=”app_background”>#FF0000FF</color>
<dimen name=”default_border”>5px</dimen>
<array name=”string_array”><item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
</array>
<array name=”integer_array”>
<item>3</item>
<item>2</item>
<item>1</item>
</array>
</resources>
This example includes all of the simple value types. By convention, resources are separated into separate
fi les for each type; for example, res/values/strings.xml would contain only string resources.
The following sections detail the options for defi ning simple resources.
Supported simple values include strings, colors, dimensions, and string or integer arrays. All simple
values are stored within XML fi les in the res/values folder.
Within each XML fi le, you indicate the type of value being stored using tags as shown in the sample
XML fi le below:
<?xml version=”1.0” encoding=”utf-8”?>
<resources>
<string name=”app_name”>To Do List</string>
<color name=”app_background”>#FF0000FF</color>
<dimen name=”default_border”>5px</dimen>
<array name=”string_array”><item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
</array>
<array name=”integer_array”>
<item>3</item>
<item>2</item>
<item>1</item>
</array>
</resources>
This example includes all of the simple value types. By convention, resources are separated into separate
fi les for each type; for example, res/values/strings.xml would contain only string resources.
The following sections detail the options for defi ning simple resources.
Strings
Externalizing your strings helps maintain consistency within your application and makes it much
easier to create localized versions.
String resources are specifi ed using the string tag as shown in the following XML snippet:
<string name=”stop_message”>Stop.</string>
Android supports simple text styling, so you can use the HTML tags <b>, <i>, and <u> to apply bold,
italics, or underlining to parts of your text strings as shown in the example below:
<string name=”stop_message”><b>Stop.</b></string>
You can use resource strings as input parameters for the String.format method. However,
String.format does not support the text styling described above. To apply styling to a format
string, you have to escape the HTML tags when creating your resource, as shown below:
<string name=”stop_message”><b>Stop</b>. %1$s</string>
Within your code, use the Html.fromHtml method to convert this back into a styled character
sequence:
String rString = getString(R.string.stop_message);
String fString = String.format(rString, “Collaborate and listen.”);
CharSequence styledString = Html.fromHtml(fString);
Externalizing your strings helps maintain consistency within your application and makes it much
easier to create localized versions.
String resources are specifi ed using the string tag as shown in the following XML snippet:
<string name=”stop_message”>Stop.</string>
Android supports simple text styling, so you can use the HTML tags <b>, <i>, and <u> to apply bold,
italics, or underlining to parts of your text strings as shown in the example below:
<string name=”stop_message”><b>Stop.</b></string>
You can use resource strings as input parameters for the String.format method. However,
String.format does not support the text styling described above. To apply styling to a format
string, you have to escape the HTML tags when creating your resource, as shown below:
<string name=”stop_message”><b>Stop</b>. %1$s</string>
Within your code, use the Html.fromHtml method to convert this back into a styled character
sequence:
String rString = getString(R.string.stop_message);
String fString = String.format(rString, “Collaborate and listen.”);
CharSequence styledString = Html.fromHtml(fString);
54
Chapter 3: Creating Applications and Activities
<item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
</array>
<array name=”integer_array”>
<item>3</item>
<item>2</item>
<item>1</item>
</array>
</resources>
This example includes all of the simple value types. By convention, resources are separated into separate
fi les for each type; for example, res/values/strings.xml would contain only string resources.
The following sections detail the options for defi ning simple resources.
Strings
Externalizing your strings helps maintain consistency within your application and makes it much
easier to create localized versions.
String resources are specifi ed using the string tag as shown in the following XML snippet:
<string name=”stop_message”>Stop.</string>
Android supports simple text styling, so you can use the HTML tags <b>, <i>, and <u> to apply bold,
italics, or underlining to parts of your text strings as shown in the example below:
<string name=”stop_message”><b>Stop.</b></string>
You can use resource strings as input parameters for the String.format method. However,
String.format does not support the text styling described above. To apply styling to a format
string, you have to escape the HTML tags when creating your resource, as shown below:
<string name=”stop_message”><b>Stop</b>. %1$s</string>
Within your code, use the Html.fromHtml method to convert this back into a styled character
sequence:
String rString = getString(R.string.stop_message);
String fString = String.format(rString, “Collaborate and listen.”);
CharSequence styledString = Html.fromHtml(fString);
Colors
Use the color tag to defi ne a new color resource. Specify the color value using a # symbol followed by
the (optional) alpha channel, then the red, green, and blue values using one or two hexadecimal numbers
with any of the following notations:
❑ #RGB
❑ #RRGGBB
❑ #ARGB
❑ #ARRGGBB
The following example shows how to specify a fully opaque blue and a partially transparent green:
<color name=”opaque_blue”>#00F</color>
<color name=”transparent_green”>#7700FF00</color>
Chapter 3: Creating Applications and Activities
<item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
</array>
<array name=”integer_array”>
<item>3</item>
<item>2</item>
<item>1</item>
</array>
</resources>
This example includes all of the simple value types. By convention, resources are separated into separate
fi les for each type; for example, res/values/strings.xml would contain only string resources.
The following sections detail the options for defi ning simple resources.
Strings
Externalizing your strings helps maintain consistency within your application and makes it much
easier to create localized versions.
String resources are specifi ed using the string tag as shown in the following XML snippet:
<string name=”stop_message”>Stop.</string>
Android supports simple text styling, so you can use the HTML tags <b>, <i>, and <u> to apply bold,
italics, or underlining to parts of your text strings as shown in the example below:
<string name=”stop_message”><b>Stop.</b></string>
You can use resource strings as input parameters for the String.format method. However,
String.format does not support the text styling described above. To apply styling to a format
string, you have to escape the HTML tags when creating your resource, as shown below:
<string name=”stop_message”><b>Stop</b>. %1$s</string>
Within your code, use the Html.fromHtml method to convert this back into a styled character
sequence:
String rString = getString(R.string.stop_message);
String fString = String.format(rString, “Collaborate and listen.”);
CharSequence styledString = Html.fromHtml(fString);
Colors
Use the color tag to defi ne a new color resource. Specify the color value using a # symbol followed by
the (optional) alpha channel, then the red, green, and blue values using one or two hexadecimal numbers
with any of the following notations:
❑ #RGB
❑ #RRGGBB
❑ #ARGB
❑ #ARRGGBB
The following example shows how to specify a fully opaque blue and a partially transparent green:
<color name=”opaque_blue”>#00F</color>
<color name=”transparent_green”>#7700FF00</color>