Thursday, 30 June 2011

View visibility

How do I hide and show view controls in my app?
View controls (TextView, EditText, Button, Image, etc) all have a visibility property. This can be set to one of three values:
  • Visible - Displayed
  • Invisible - Hidden but space reserved
  • Gone - Hidden completely
The visibility can be defined in the layout XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:text="You can see me"
    android:visibility="visible" />
     android:id="@+id/button2" android:dr
    android:text="You cannot see me, but you can see where I am"
    android:visibility="invisible" />
    android:text="You have no idea that I am here"
    android:visibility="gone" />

For the LinearLayout above, the three buttons laid out horizontally with equal weights will be displayed as below. You can see the first, the space for the second, but not the third:

To set the visibility in code use the public constant available in the static View class:

Button button1 = (TextView)findViewById(;

You see?

Wednesday, 29 June 2011

Quick Tip: Copyright symbol in a string

Very quick tip; to display the copyright symbol in your app, you can use Unicode definition in a string, as shown below:

    android:text="\u00A9 Android Elements 2011" />

Displaying the copyright notice in an app

Wednesday, 22 June 2011

Opening call dialog

How do I make my app call a phone number?
The easiest method is to create an intent which opens the device caller dialog. Because this is not actually initiating the call, no additional permissions are required by your app.

final String phoneNumber = "01234 123456";
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)));

Android dialler intent

Monday, 20 June 2011

How to close soft keyboard on button press

How can my app hide the soft keyboard when a button is pressed?
A simple example of this requirement would be a search box within your app. This would be defined in your layout markup as a EditText view and a Button view. Once the user has entered some text, they will typically click on the search button. Default behaviour is that the soft keyboard is still visible until the user dismisses it. You can hide the keyboard using the following code, probably on the button click handler:

InputMethodManager inputMgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
EditText editText = (EditText)findViewById(;
inputMgr.hideSoftInputFromWindow(editText.getWindowToken(), 0);

The method requires a reference to the EditText view that was the source of the soft keyboard launch.

Wednesday, 15 June 2011

First Steps: Returning values from an Activity

How do I return  a value from an Activity?
Below is some simple example code for creating a new Intent to launch an Activity named Activity1. Here we use the startActivityForResult method which takes the intent and an identifier (an arbitrary integer):
final static int REQUEST_CODE = 1234;

private void startActivity() {
  Intent myIntent = new Intent(getBaseContext(), Activity2.class);
  startActivityForResult(myIntent, REQUEST_CODE);

In your second activity you should use the following code to return a result value and terminate the activity:

Returning to your first activity and override the activity's onActivityResult method as below. Check the result code to determine the result is coming from the expected source then you can read resultCode and change logic depending upon its value:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if(requestCode == REQUEST_CODE) {
    // Do something with resultCode

It is worth noting that you can not open activities (or dialogs for that matter) in a modal fashion, in fact nothing is modal in android as that would lock the UI which is not permitted. Listeners are always used to receive the results.

Tuesday, 14 June 2011

First Steps - Passing values to an Activity

How do I pass a value to an activity?

To start an Activity you use an Intent. In this intent you can pass data which is returned as a Bundle object.

Android Activities and Intents

Below is some simple example code for creating a new intent to launch an Activity named MyActivity. Note the call to the putExtra method which accepts a key name ("content") and a value:

Intent myIntent = new Intent();
String packageName = this.getPackageName();
packageName + "." + MyActivity.class.getSimpleName());
myIntent.putExtra("content", "my content string");

Here is the code for the called activity with the Bundle data extracted from the intent. You can then retrieve the passed extra content from the bundle object:

public class MyActivity extends Activity {

  public void onCreate(Bundle savedInstanceState) {

    Bundle bundle = getIntent().getExtras();
    String content = bundle.getString("content");

All pretty simple when you know how.

Monday, 13 June 2011

Android Development Tools ADT and DDMS Version 11 Release

Last week Google released a new version of the Android Development Tools (ADT). If you've not updated to version 11 yet, then DO IT NOW! There are a number of big improvements that will enhance your app development process, particularly regarding layouts and XML editing. Take a look at the video below for details of the update made at Google I/O 2011, if you've been developing on Android for a while, this should really get your juices flowing!

If you're not already then you should be following the Android Developers Blog (or @AndroidDev on Twitter).

How do update my tools in Eclipse?
Make sure you are running Eclipse as Administrator, then go to Help > Check for Updates.
Now just step through the sequence, agree to license terms then restart Eclipse when prompted.

Cannot install Android Development Tools / DDMS

If you see the following error when updating you Android Development Tools and DDMS in Eclipse on a Windows PC, you need to run Eclipse as Administrator.

"The operaton cannot be completed. See the details."

"Cannot complete the install because of a conflicing dependency."

Cannot complete the install because of a conflicing dependency

Thursday, 9 June 2011

Creating an Android Preferences Screen

How do I add a preferences / setting screen to my android app?
Thankfully it is very easy to create a preferences screen, much like those you'd find within the Settings on your handset. A preference screen requires a special XML definition, you cannot use standard layouts and views, however this can still be placed within your layout folder.

The PreferenceScreen layout can be separated into sections with a PreferenceCategory which has a title and is displayed as a dividing bar o the screen. There are several preference type views:

EditTextPreference - text box entry (text string)
CheckBoxPreference - tickable check box (true/false boolean)
ListPreference - Selection from array of options (text string)
RingtonePreference - Selection of Uri of ring tones stored on device

A simple example of a preferences screen layout is shown below:

Preferences screen
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android=""


       android:title="Option 1"
       android:summary="Tick to set this option"
       android:title="Option 2"
       android:summary="Tick to set this option"

        android:summary="Select item from array"

        android:title="Input text"
        android:summary="Tap to enter some text"
        android:dialogTitle="Enter text"

    android:summary="Open a webpage">

      android:data="" />


The ListPreference in the XML above references two arrays; one for the option text and one for the option values. These should be defined in your strings resource file:

<?xml version="1.0" encoding="utf-8"?>
    <string-array name="types">
     <item>Type 1</item>
     <item>Type 2</item>
     <item>Type 3</item>
    <string-array name="types_values">

Your activity must extend the PreferenceActivity rather than a standard activity. This should be defined as below:


import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Prefs extends PreferenceActivity {
    public void onCreate(Bundle savedInstanceState) {

Don't forget to add this activity to your manifest!
You can read and write the prefence values in code with the following method examples...

// String
    public static String Read(Context context, final String key) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
        return pref.getString(key, "");
    public static void Write(Context context, final String key, final String value) {
          SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
          SharedPreferences.Editor editor = settings.edit();
          editor.putString(key, value);
    // Boolean  
    public static boolean ReadBoolean(Context context, final String key, final boolean defaultValue) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
        return settings.getBoolean(key, defaultValue);
    public static void WriteBoolean(Context context, final String key, final boolean value) {
          SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
          SharedPreferences.Editor editor = settings.edit();
          editor.putBoolean(key, value);

Just as an aside, many apps I have build have been based upon a white theme rather than the default android dark. It is easy to set your preferences screen to use the built in Light theme so that it looks more consistent within your app, simply set the theme for the activity within your manifest as follows:

<activity android:name=".Prefs" android:theme="@android:style/Theme.Light">

Then your preferences screen will look something like this:

Preferences Screen (Light theme)

Please see my post on Introducing Themes for more information about themes and styles.

Monday, 6 June 2011

Customizing the Title Bar

How do I change the title bar for my app?
Often I find that I want to remove the Android title bar from my app entirely and create my own within the layouts. To achieve this, just set the theme for the entire application, or individual activity to Theme.NoTitleBar then set my own title bar within the layouts as required:

  <activity android:name=".Main" android:theme="@android:style/Theme.NoTitleBar" />

However, the standard title bar is fairly flexible in terms of background and text options (although centering the title text is not trivial). To modify it we start off by creating our own theme and, in this case, inherit from the default android theme. This theme contains system names for the android title styles and effectively overrides them. Where the name denotes a style, e.g. windowTitleStyle, a reference to a defined style is required.

<?xml version="1.0" encoding="utf-8"?>
  <style name="Theme.myTheme.TitleBar" parent="android:Theme">
    <item name="android:windowTitleBackgroundStyle">@style/windowTitleBackgroundStyle</item>
    <item name="android:windowTitleStyle">@style/windowTitleStyle</item>
    <item name="android:windowTitleSize">50dip</item>

<?xml version="1.0" encoding="utf-8"?>
  <style name="windowTitleBackgroundStyle">  
    <item name="android:background">@FF000</item>                
  <style name="windowTitleStyle">
    <item name="android:textColor">#FFFFFF</item>
    <item name="android:padding">12dip</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textSize">16sp</item>

Finally set the theme within the manifest for either the application or individual activities...

  android:theme="@style/Theme.myTheme.TitleBar" >

Thursday, 26 May 2011

First Steps - Introducing Themes

How do I use themes in my app?
This post extends my previous post introducing styles, so if you've not used styles in android before I would recommend reading that first.

A theme is specified for an entire application or individual activities within the manifest. It encapsulates a number of visual style settings, such as text and button styling.

Android has a default theme which is the 'dark' theme, black background with white text, that you will see it you were to open the Settings menu for example. When you create an android app you do not need to specify the theme as the dark theme is used by default.

It is likely that you will at some point want to hide the application title bar, this can be done by setting the theme to Theme.NoTitleBar. Android also has a 'light' theme built in (black on white) which can be used by setting the theme to Theme.Light. You can also chain the theme settings to allow combinations, for example Theme.Light.NoTitleBar. Themes are applied in the manifest as shown below:

Manifest sample:

System styles are prefixed for the @android tag. Much like styles, custom themes are defined within an XML file within your resources and each theme must have a name and can optionally have a parent, for inheriting properties:

<?xml version="1.0" encoding="utf-8"?>
    <style name="Theme.myTheme" parent="android:Theme.Light.NoTitleBar">
     <item name="textSize">20sp</item>

You can then apply your own theme within your project manifest, as shown below.

Manfiest sample:

Wednesday, 25 May 2011

First Steps - An introduction to Styles

How do I use styles in my app?
Use of styles allows you to define reusable visual settings to help maintain a consistent look-and-feel to your app.
The simple example below shows how to create a style for titles, which will be larger text, and warnings which will be red. Each style must have a name and can then list multiple properties:

<?xml version="1.0" encoding="utf-8"?>
    <style name="myTitle">
      <item name="android:textSize">16sp</item>
    <style name="myWarning" parent="@style/myTitle">
      <item name="android:textStyle">bold</item>
      <item name="android:textColor">@colors/myRed</item>

A few things to note here, firstly that you can put any styling name into the item tag that you would use within your layout definitions. Also note that myWarnings has its parent set as myTitle and so inherits the 16sp text size defined there. Finally, the textColor value could be a standard hex colour (i.e. #FF0000) but it is good practice to put colours into a separate resource so that one you only need to update one location if you want to change it:

<?xml version="1.0" encoding="utf-8"?>
    <color name="myRed">#FF0000</color>

Now it is simply the case of applying the style within your layouts:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
        android:layout_height="wrap_content" >

        android:text="My styled text view"
        style="@styles/myWarning" />

Note that the style attribute is not prefixed by the android tag.

Tuesday, 24 May 2011

Referencing a drawable in code

A very quick one here, but I often forget how to get a reference in code to my drawable resources, so here it is...

Drawable d = getResources().getDrawable(R.drawable.icon);

The getResources() method available depending upon context. If you need to reference it from within your own class then you'll need to pass a context in.

First Steps Series, Getting Started with Android

My First Steps guides are intended to assist those new to Android development. I thought I should have an index of them all, so here it is.

1. Welcome to Android Elements
A welcome and how to get started with links to good resources.

2. Android Building Blocks
The basics of how an app is structured.

3. My First Android Project
Walkthrough of building your first project; a simple app with a button.

4. My Second Android Project
Extending the simple app using addition controls and settings.

5. Common Pitfalls
Common pitfalls and how to avoid them.

6. Android Project Structure in Eclipse
An overview of the structure of an Android project within Eclipse.

7. Introduction to Styles
Simple guide to using styles when building an app.

8. Introducing Themes
Expansion of introduction to styles into themes.

9. Passing values to an Activity
Simple example of passing values into an Activity using an Intent.

10. Returning values from an Activity
Simple example of returning a value from an Activity.

I will continue to add to the series over time,

Monday, 23 May 2011

Displaying the Version number of your app

How do I display the versionName from my manifest file in my app?

The versionName value in your project manifest file is a 'friendly' version number that is displayed to the user on the market screen and in the application list. The versionCode value is the integer that allows you to version and publish updates to your app on the market (refer to the official documentation on Versioning Your Applications).

<manifest xmlns:android=""

You might want to display the version name in your app, on a splash or about screen perhaps. To do this you need to use the PackageInfo class, here's how...

Add the following imports:

Use the following code to display the value in a TextView:
String versionName = "";
try {
    final PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    versionName = packageInfo.versionName;
} catch (NameNotFoundException e) {
TextView tv = (TextView) findViewById(;

Sunday, 22 May 2011

Defining a custom button with background and textcolor styles

How do I define a custom button with background and text color styles?

This is a simple guide to styling buttons within your Android app. We start of with a button in your Layout, and set the style to a custom style name:

  android:text="Tap me!"
  style="@style/button" />

It is a good idea to use a style rather than set the background directly as it allows you to set the text properties as well as background graphic options. It also makes it very easy to re-use your style.

<style name="button">
  <item name="android:background">@drawable/button</item>
  <item name="android:textColor">#FFF</item>
  <item name="android:textSize">16sp</item>
  <item name="android:gravity">center_vertical|center_horizontal</item>

The background of a Button is expected to be a Drawable (image), but we are able to define this as a shape with an item for each state (pressed, focussed or default). To keep this simple we'll stick to simple colour changes:

<?xml version="1.0" encoding="utf-8"?>    
<selector xmlns:android="">

  <item android:state_pressed="true" >
      <solid android:color="#FF0000" />

  <item android:state_focused="true" >
      <solid android:color="#DDDDDD" />

      <solid android:color="#FFFFFF" />


You may want to produce more fancy buttons, in which case you will need to use more shape options (such as rounding and strokes) or produce a Drawable image for each state. If you want to use images, these should be 9-Patch PNGs that allow Android to stretch the image to fit any content. I will cover these another day!

Thursday, 19 May 2011

Advanced Lists: Using class object within ListView

How do I build a ListView to display my custom class items?

One of the most common interface elements used in Android apps is the ListView. This presents to the user a scrollable list of tappable items. The best place to start with this is and Android Developers ListView Tutorial which will cover the basics of creating an activity with the ListView control and displaying a list of items from a string array.

In a real world app you will probably want to build a list with something other than a string array. Commonly you will have a collection of your own type of object, or you may want to display listview items with an icon. I will show you how to use a ListView to display these objects and also handle the tap event.

Let's start with the class object that will consist of a text label, a drawable for the icon and also an index value to track item selection:
package com.example.advancedList; import; public class CustomListItem { private int mIndex; private String mLabel; private Drawable mPicture; public CustomListItem(final int index, final String label, final Drawable pic) { mIndex = index; mLabel = label; mPicture = pic; } public int getIndex() { return mIndex; } public String getLabel() { return mLabel; } public Drawable getPicture() { return mPicture; } }
Now that we have our class defined, let's create the layout that will be used to display the individual list item, which is a simple RelativeView with an ImageView for the icon and a TextView for the label:

Create res/layout/list_item.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
       android:text="List item" />
       android:layout_toRightOf="@id/txtLabel" />

Hopefully so far everything has been quite straight forward. We now need to define a custom list adapter that extends the BaseAdapter class, this will allow us to fully control the way the ListView is constructed.

Create a class named
package com.example.advancedList;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

// Custom list item class for menu items
public class MyListItemAdapter extends BaseAdapter {

    private List<CustomListItem> items;
    private Context context;
    private int numItems = 0;

    public MyListItemAdapter(final List<CustomListItem> items, Context context) {
        this.items = items;
        this.context = context;
        this.numItems = items.size();
    public int getCount() {
        return numItems;

    public CustomListItem getItem(int position) {
        return items.get(position);

    public long getItemId(int position) {
        return 0;

    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the current list item
        final CustomListItem item = items.get(position);
        // Get the layout for the list item
        final RelativeLayout itemLayout = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
        // Set the icon as defined in our list item
        ImageView imgIcon = (ImageView) itemLayout.findViewById(;
        // Set the text label as defined in our list item
        TextView txtLabel = (TextView) itemLayout.findViewById(;

        return itemLayout;

Next let's knock together a simple layout for the main activity. This will consist of a ListView for our items and a TextView that is displayed if the list is ever empty. Note here the use of special Android reserved IDs for the controls. This allows the list to be picked up for the ListActivity we'll use and also know to only display the TextView if there is no data in the ListView.

We'll call the file res/layout/list_example.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""

      android:layout_width="fill_parent" />
      android:text="Nothing to list" />

We now need to build our main Activity which extends the ListActivity class using our layout defined previously. Within the activity's onCreate method we create a List of our CustomListItem type and add 3 new items to it. We then populate a new ListAdapter using our myListItemAdapter class and assign to it our list of items:

src/com.example.advancedList/ :
package com.example.advancedList;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class Main extends ListActivity {

    public void onCreate(Bundle savedInstanceState) {
// Create list of items based upon class
        final List<CustomListItem> items = new ArrayList<CustomListItem>(3);
        items.add(new CustomListItem (1, "Item 1", getResources().getDrawable(R.drawable.icon)));
        items.add(new CustomListItem (2, "Item 2", getResources().getDrawable(R.drawable.icon)));
        items.add(new CustomListItem (3, "Item 3", getResources().getDrawable(R.drawable.icon)));
        // Populate the list view
        ListAdapter adapter = new myListItemAdapter(items, this);
        ListView lv = getListView();  // Because we are extending ListActivity we cal  this but could specify
        // Add listener for item clicks
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                  // Retrieve our class object and use index to resolve item tapped
                    final MenuListItem item = items.get(position);
                    final int menuIndex = item.getIndex();
                    switch (menuIndex) {
                    case 1:                      
                    case 2:                      
                    case 3:

You'll see that once we have our list adapter set up it is applied to the list view. We then assign a listener to the list view to pick up click events. Within this the first thing we do it obtain the item from the list that was clicked. We then have the freedom to make our code react to any aspect of our object.

I have used this approach several times and in fact have never displayed a list from a string array. I hope you find this guide useful.

Tuesday, 17 May 2011

Best Eclipse Shortcuts

There are many sites listing their top Eclipse shortcuts, but for what it's worth I would like to add my most used keyboard shortcuts since starting with Eclipse...

Ctrl + Shift + O = organise and import missing imports
Alt + Shift + R = refactor (rename variable or method)

Ctrl + 1 (one) = Quick fix popup
Ctrl + D = Delete line
Ctrl + O = Outline (easily navigate to parts of project)
Ctrl + M (or double-click tab) = Maximise source when coding
Ctrl + . = Jump next error or warning

Alt + UP / Alt + DOWN = Move selection up or down
Alt + LEFT / Alt + RIGHT = Jump to recently edited sections

Ctrl + Shift + R = open resource (start typing any file name - like indexed search)
Ctrl + Shift + F - Formats code to settings defined under Window > Preferences > Java > Code Style > Formatter

Monday, 16 May 2011

Setting a style on dynamically created view control

How do I set a TextView or Button style in code?
Styling within Android allows you to define a reusable look-and-feel, much like styles in CSS on a web page. These are very easy to assign in your XML layouts, however you cannot set the style of a View control programmatically. This is a pain if you are building a layout dynamically.

To get around this you can create a template layout xml file with the style assigned, for example in res/layout create tvtemplate.xml as with the following content:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android=""
        android:text="This is a template"
        style="@style/my_style" />

then inflate this to instantiate your new TextView:

TextView myText = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);

You can then continue to work with your TextView as usual. There may be other workarounds for this, if you have any please feel free to comment. It's also possible that an Android API update will add a property for this in future.

Wednesday, 11 May 2011

Adding views to a layout dynamically

How do I add a button to my layout in code?

Firstly add the appropriate import to your Activity class for the view to add, in this case a button:

import android.widget.Button;

Then create a new button object within the activity onCreate method:

Button myButton = new Button(this);
myButton.setText("Tap Me");

Finally add the button to the layout:

LinearLayout layout = (LinearLayout) findViewById(;

Obviously the same logic applies to other views (TextViews, etc).

You might also want to apply fonts to your controls, if so take a look at Using a True-Type Font in your Android app.

Tuesday, 10 May 2011

Official Android Ice Cream Sandwich image

Tweeted by @AndroidDev earlier today at IO2011...

Share photos on twitter with Twitpic

First Steps: Android project structure in Eclipse

Android Project structure in Eclipse
This article is a quick guide to the breakdown of the project structure of a typical, simple Android project within Eclipse. The numbered items below refer to the image to the right.
  1. Project root folder (see 7 for details of individual files)
  2. src folder. This is where your java code files are stored.
  3. package folder. This is organised by package name with the java class files within.
  4. is a java class file, in this case the main activity. Note the exclamation denoting a compilation warning.
  5. is another java class (without warnings or errors).
  6. gen folder. The generated compiled files when a project is built. You do not need to venture into this folder.
  7. Google APIs folder. The API library folder.
  8. assets folder. This is where you place additional assets for use in your project, such as font (ttf) files.
  9. res folder. This is where the resource files are stored, such as your drawables (images), layouts and string values.
  10. drawable-hdpi folder. High density drawables (images) for use in your project.
  11. drawable-ldpi folder. Low density drawables (images) for use in your project.
  12. drawable-mdpi folder. Medium density drawables (images) for use in your project.
  13. layout folder. This contains the XML layout files that define the screens in your project.
  14. main.xml. This is the layout for the Main activity, defined in
  15. web.xml. This is the layout for the Web activity, defined in
  16. values folder. This is where your string (text) definitions are stored. To support multiple languages you would find a values folder per language, for example values-fr.
  17. strings.xml. A standard XML file containing named string definitions.
  18. AndroidManifest.xml - The hub of your project containing the details on the Activities, Permissions within your app.
  19. -An auto-generated configuration file storing the basic project properties.
  20. proguard.cfg - ProGuard can be used to obfuscate your code to prevent nasty code thieves from stealing your secrets. By default this is not applied to the code but the configuration file is still present.
Typically you will place any additional referenced Java libraries (.jar files) into a libs folder.

Hopefully this will help an Android newbie opening up a new project for the first time.

Friday, 6 May 2011

Using a True-Type Font in your Android app

Android supports true-type fonts, but these have to be set in code, you cannot specify the fonts in the layout XML.

Firstly copy the font file into your assets folder. I usually create a fonts sub-folder:


Second, and finally, apply the font to a TextView in code:

TextView tv = (TextView)findViewById(;
Typeface face = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");

TextViews, Buttons, CheckedTextView and RadioButtons all have the setTypeface method, but as a note of warning, not all .ttf files will necessarily display in your Android app, if it fails your app will force close with the following error: RuntimeException: native typeface cannot be made.

Wednesday, 4 May 2011

How to Fix Screen Orientation

How do I stop my Android app rotating?

There are a number of reasons that you may want to prevent your screen from rotating. When an Android device is rotated, by default the currently running activity is restarted. This will often require you to code to maintain the state that the activity was in prior to rotation. Alternatively you may simply want to display only in landscape, perhaps for a game.

To fix your screen orientation, simply set the screenOrientation attribute of the activity within your project manifest, as shown below, to either portrait or landscape:


You can also do the same thing in code:


Please refer to the official documentation for more details.

Thursday, 28 April 2011

Regular Expressions in Android

If you are not familiar with regular expressions, then it is well worth spending some time finding out about them. Basically a regular expressions allow you to define a and search for a pattern of text within a string, to pick out an email address for example. Head over to and find out more, it may seem overly complicated at first, but you will often find you cannot do without them. There are also plenty of sites for testing patterns against, is a good simple one.

Right, let's get to the code. To handle regular expressions in Android you use the standard Java classes, so if you are familiar with these then there is nothing more to learn. Otherwise, the first thing to do is add the following import references to your class:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

My example method will match a defined pattern in the variable myString. If a match is found then the first match (there may be more than one) is returned for use:

private String findMatch(String myString) {

    String match = "";

    // Pattern to find code
    String pattern = "[0-9]{8}";  // Sequence of 8 digits
    Pattern regEx = Pattern.compile(pattern);

    // Find instance of pattern matches
    Matcher m = regEx.matcher(myString);
    if (m.find()) {
        match =;
    return match;

Hopefully this simple guide is enough of an introduction to the basics to get you going. There are many good resources on the web to help you build patterns and also libraries of commonly used patterns, for example. Now you'll be knocking out expressions in no time!

Thursday, 21 April 2011

Adding a Menu to your Android app

Adding an Android Menu to your app that opens when the hardware menu button is pressed

This is very simple so we'll jump straight into the XML file that defines the menu. Typically menu XML definitions will be kept in a menu folder within the resources folder; res. Create the directory if it is missing and add a new XML file called 'example.xml'.

The following full path should now exists within your project:


Open the XML file and paste in XML below. Here we are defining a menu with a single item labelled "Refresh". This item has an icon, but this is not a requirement:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="">
<item android:id="@+id/menu_refresh"
      android:title="Refresh" />

Now open the activity class that you want to include the menu in. Add the following imports at the top of the class:

import android.view.Menu;
  import android.view.MenuInflater;
  import android.view MenuItem;

Two methods are required within your activity class, the first creates the menu options by inflating the xml definition we created:

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(, menu);
        return true;
The second method handles the menu item selection. Here I use a case statement to react in response to the ID of the tapped menu item:

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // Refresh something
            return true; 
            return super.onOptionsItemSelected(item);

Now run your app and hit the menu button and you should see something like this...

Android app with menu

For more detail please refer to the Android Developer Creating Menus guide.

Monday, 18 April 2011

Quick Tip: Opening a URI in the web browser

Below is example code to open a web page URI / URL in the web browser:

  String webPageUri = "";
  Uri uri = Uri.parse(webPageUri);
  if (uri != null) {
    Intent myIntent = new Intent(Intent.ACTION_VIEW, uri);

First we parse the uri string. If we have a non-null value we create a new Intent object set to use ACTION_VIEW with the uri as a parameter. ACTION_VIEW will perform the appropriate action for the contents of the provided uri. Then we call a method to start the new activity with this intent object.

Finally, we must ensure the app has internet access to call a web page (see my list of common Android pitfalls) so add the following permission to the manifest:

<uses-permission android:name="android.permission.INTERNET" />

Review the Android Developers site for more on intents and my Android Building Blocks guide for getting started.

Android Versions

Android Platform Versions, API Levels and Names

Each Android platform release or update is given an incremental API version and also the name of a dessert, to make discussions on the subject easier to swallow (ho ho). The dessert names run in alphabetical order and are always hotly speculated prior to release.

The table below lists the Android versions with their API level and also dessert name. The list strikes-through versions that were not released or are declared obsolete:

Platform Version   API Level    Name
4.014Ice Cream Sandwich
4.015Ice Cream Sandwich
4.113Jelly Bean

It is always worth keeping and eye on the latest Android Platform Versions statistics provided by Google.

How do I find the Android platform version my app is running on?

In your app you can test for the version of Android that is running with the following code:

if(android.os.Build.VERSION.SDK_INT < 8) {
    // Do something for versions less than 2.2

Thursday, 14 April 2011

First Steps (5) Common pitfalls

Common pitfalls and how to avoid them.
Below I have listed the pitfalls that have caught me out most often since starting in Android development. Hopefully this short checklist of rules will help you quickly skip over basic problems...

Yes I did shout that. In the early days this caught me out countless times and still from time-to-time now. The Android manifest file is the code of your app and holds it all together. Activities must be listed in the manifest as well as the permissions you app requires.

When you add a new activity to your project you'll need to add an activity entry to the manifest. Refactor or rename an activity and your code will be nicely updated, but not your manifest. It's easy to fix, but you'll just kick yourself each time it happens, mostly because the project will happily build and it won't show itself until you get a nasty force close.

In addition you may be adding code that requires a permission. The most common is probably internet access. If you forget to add this permission to the manifest then you will see "Permission Denied" errors. If you're doing something like hitting a web service it can sometimes take a few moments to sink in where the permission problem lies and you'll kick yourself again!

Rule 2: Keep it Clean
Resource file changes are not available within your code immediately, you must clean up your project to refresh the references. For example, if you add a value to your res/values/string.xml file call 'bob', initially your code will make R.string.bob as an error. 
To fix this you need to clean which recompiles the resources.
From the Eclipse menu, pick Project > Clean...

This call also remove any lingering errors that are being reported but may have been resolved.

Rule 3: Don't forget your XML header and first node type in your layouts
All of your XML resource files must start with an XML version node (line 1, below) and the first node must contain an Android XML namespace attribute (line 2, below). Your resource file will not compile without these.

<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android=""

Rule 4: Look out for Android.R
Sometimes when you paste or reference from another project an 'import' reference to the Andriod.R resources is added to your code. This then means that when you try to reference your own resource with R.something the API looks for a reference in the Android.R namespace and warns you it cannot be found.

Simply remove the 'imports Android.R;' line from your class. Another easy fix, but can be confusing when it happens.

Rule 5: For String comparisons use .equals
When comparing strings, use myString1.equals(myString2) rather than "==" (double equals) as this will avoid comparison problems. Use equalsIgnoreCase for case-insensitive comparisons.

Rule 6: Check for emulator internet access
Sometimes, inexplicably, the network availability is lost on my emulator. Again, this is very easy to miss and can drive you to insanity trying to determine why things have stopped working. Just keep an eye on connection status in the notification area of the emulator to avoid this.
The emulator connection can drop for no reason
Rule 7: View items missing from LinearLayout
If you create a linear layout and find that only the first view (a TextView for example) is showin, it probably means you haven't set the orientation. If the width of the first view is set to fill/match parent and the orientation is not defined then all subsequent views will be rendered off-screen to the right.

<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android=""
<!-- You won't see the following view if the orientation is horizontal or not set -->

Rule 8: DON'T PANIC!
Yes, I shouted again. On occasion I have seen my list of errors suddenly go through the roof after only a minor change. This usually boils down to a small XML change (layout, or other resource) that resulted in some invalid mark-up and suddenly your project looks a mess. Take a deep breath, try to think what you've changed and take a look at the first error or so in the list. It may just be that you've missed a quote or an angle bracket.

So, that's my list so far. Any further suggestions are welcomed. I hope it saves someone some of the pain I went through during my first steps.

Tuesday, 12 April 2011

First Steps (4) My Second Android Project

Extending a simple Android App to add a new WebView.Introducing: Activity, Intent, Layout, Manifest, WebView, UsesPermission

In this tutorial I will expand on my previous guide to building My First Android Project to add a new screen containing some web content You can continue from the code we had completed at the end of that project, which was a single Activity with a Button that invoked a Toast message. Alternatively you can start a new project and use this guide.

The aim of this second project is to add an additional Activity with a WebView control that displays a web page or HTML content. We will also have a look at the manifest file as we will require permission to access the web. Are you sitting comfortably?...

1. Open your MyAndroidProject project, or create a new project.

2. First we add a class that will be our new Activity. In Eclipse right-click on the project and select New > Class.

3. Complete the following information in the New Java Class form:

Source folder: MyAndroidProject/src
Package: com.androidelements.MyAndroidProject
The package namespace of our project.
Name: Web
The name of our new class.
We are going to extend the Android Activity class.

Finally, untick the "Inherited abstract methods" tickbox so that we get an empty class definition and click on Finish.

4. The new activity will have been created inheriting from the Android Activity class, but without the onCreate method that is required for an activity. Copy and paste this from your activity or type in  the following so that the class is as below.

package com.androidelements.MyAndroidProject;

  import android.os.Bundle;

  public class Web extends Activity {

    public void onCreate(Bundle savedInstanceState) {

5. We need this activity to use a new layout, so ensure that the setContentView method is set to use a layout called "web":


6. The web layout does not yet exist so we need to create it by on the New Android XML File button in the menu:

7 Complete the New Android XML File wizard with the following information:

Project: MyAndroidProject
File: web.xml
What type of resource configuration would you like?: Layout
Folder: /res/layout
Select the root element for the XML file: LinearLayout

Click on the Finish button.

8. The web.xml will now be opened in the Graphical Layout view. Switch to the xml view by selecting the tab at the bottom of the screen labelled "web.xml".

9. Within the XML add a WebView. A view always requires a width and height. The values for these are one off fill_parent/match_parent (fill the space), wrap_content (use required space) or a fixed, defined size.

<?xml version="1.0" encoding="utf-8"?>



Note the id specification, the @ (at) symbol denotes an id, and the + (plus) denotes that it should be added to the resource file (only supported on id declaration).

10. Save your new files and return to the code. You should see that the content setContentView declaration has a red warning underline under "web" of R.layout.web. This is because the resource file, R, has not been recompiled. To resolve this we need to 'clean' the project:

From the menu bar select Project > Clean...

11. In the Clean dialog, select "Clean projects selected below", tick the MyAndroidProject project, tick "Start a build immediately" and select "Build only the selected projects". Click OK.

After the clean has taken place the warning should be removed and the word "web" will display in italicised blue.

12. Now we want to add some code to set the contents of the web view. Add the following line under the setContentView method:

    public void onCreate(Bundle savedInstanceState) {
        WebView web1 = (WebView)findViewById(;             

This line defines a variable of type WebView and assigns it to the view in the layout by specifying the resource id as a parameter to the findviewById method.

13. Initially the words WebView will be underlined red because no reference to these object types exists in this Activity class. Hover your mouse cursor over the WebView keyword and a list of fixes will be displayed. Click on "Import 'WevView' (android.webkit).

This will add the following import reference to the top of your class (alternatively you can type this in yourself):

import android.webkit.WebView;

14. Now add a line to set the web view to display a web page:

    public void onCreate(Bundle savedInstanceState) {
        WebView web1 = (WebView)findViewById(;

15. Now we need to specify our new Activity and internet permission in the manifest. Open the Android.manifest file from the Package Explorer and switch to the XML view (bottom tab).

16. Add our new lines, the first defining the Activity and the second requesting internet access permission:

<?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android=""
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Main"
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
        <activity android:name=".Web" android:label="@string/app_name" />
    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.INTERNET" />
17. Open the file. We are going to change our button click to launch the new Activity. This is done be creating a new Intent object, assigning a class name and then requesting the start of an activity:

package com.androidelements.MyAndroidProject;

  import android.content.Intent;
  import android.os.Bundle;
  import android.view.View;
  import android.widget.Toast;

  public class Main extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
    public void clicked(View view) {
        Intent myIntent = new Intent();
        myIntent.setClassName("com.androidelements.MyAndroidProject", "com.androidelements.MyAndroidProject.Web");

18. Launch the AVD (Android Virtual Device) and run the app. You should see the screen with the single button. Click the button and you should see our new activity, wait a few seconds for the page to load and voila, you have a web page rendered within your app...

Saturday, 9 April 2011

First Steps (3) My First Android Project

Here I will run through the steps for creating your first Android project. I assume that you have a fully installed Eclipse with Android SDK environment and you know how to create an AVD (Android Virtual Device).

1.Open Eclipse then select from the top menu; File > New > Other...

2. Select Android Project, which is under the Android folder in the list:

3. Fill in the required project properties:
  • Project name: MyAndroidProject
    Project name within Eclipse and folder name within the workspace.
  • Contents: (leave as defaults)
  • Built Target: Google APIs 2.2
    The target version of the Android SDK. Generally I target the most common Android version running. (currently 2.2)
  • Application name: MyAndroidProject
    The name of the app which displayed to the user and below the icon on the device.
  • Package name: com.androidelements.MyAndroidProject
    The namespace of your project. The convertion is to have your company name followed by the project name with a three character type prefix (com, meaning company).
  • Create Activity: Main
    The name of the first activity to load.
  • Min SDK Version: 8
    The minimum Android SDK version to support. Using the same as the target version for this example.

4. Click Finish (skipping the Test creation step for this example).

The project is now created and available within Eclipse.

5. Expand the "src" (source) folder, then the package folder and you will see the activity class. Double-click on this to view the code within Eclipse. You should see the following code

package com.androidelements.MyAndroidProject;


public class Main extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {

This is our Activity called "Main" which is inheriting from the Activity class. The onCreate method is called when the activity starts. Note that the setContentView method has the parameter R.layout.main.
R is the generated resources file and the reference is to the main.xml file in layout.

5. Expand res - layout then double-click main.xml

You will see a preview of the layout in the Graphical Layout window which will display "Hello World, Main!". Click on the tabe below this which is labelled "main.xml". The XML will now be visible:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""

This is a 'linear' layout with a single TextView element. A linear layout stacks 'views' elements in the order they are decalred. The text view is a label.

6. We are going to add a button to this layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:text="Click me"

7. Save and close the XML file to return to the code. We need to add the handler for the clicked event called by the button. This method must take one parameter that contains the reference to the calling View (the button in this case):

    public void clicked(View view) {
        Toast.makeText(this, "Clicked", Toast.LENGTH_SHORT).show();

8. You will require 2 import references at the top of the code to refer to the View and Toast classes.

    import android.view.View;
    import android.widget.Toast;

9. Now we are ready to launch the app. Click on the Android SDK and AVD Manager from the toolbar (or Window menu)

10. Select an AVD (Android Virtual Device) that is configured for the platform and API versions 8 then click on the Start.. button then on the next screen leave the default and click Launch.

11. Now click the "Run As" button (it looks like a standard play button) then select Android Application and click the OK button.

12. Your app should now load within the emulator. Click your "Click me" button and the toast message should appear.

And that is it. Simples.

Friday, 8 April 2011

First Steps (2) Android Building Blocks

As a developer with a long background in Microsoft technologies (VB then .NET and C#) moving to Android Java development was initially a bit of a challenge. Not least because I was required to stray from the comforts of my Visual Studio environment.

Having already traversed (or perhaps transcended?!) the bridge I thought I would impart some knowledge that may make the transition easier for others.

Building Blocks

When first creating an app you have to deal with Activities. These are essentially blocks of code that deal with user interaction. Coming from a Windows background it is easy to think of these as your Forms.

The interaction between activities are dealt with by Intents. These are a request for a type of action (start a new activity, launch camera, start an SMS, etc) and can also contain a Bundle which in WinForms terms would be your argument array.

Figure 1: Android Activity and Intent usage
Foundation Block

The thing that binds your project together is the manifest file which resides in the project root and is named AndroidManifest.xml. This defines the requirements, components and permissions of your app.You can think of this as your .NET app/web.config. I will being covering this in details as well as the overall project structure in a separate post.

To Conclude

Once you understand these key terms you have a good starting point for approaching your first "Hello World" project. With the aim of keeping my posts concise I will tie it up there, but please continue to follow the series.

First Steps (2) .NET Developer Moving to Android

This post has been renamed and moved to Android Building Blocks.

Thursday, 7 April 2011

First Steps (1) Welcome to Android Elements

Hello and Welcome to Android Elements. The aim of this blog is to assist those who are new to Android development, having already trodden the path myself. Posts will provide concise information and examples whilst pointing out potential pitfalls and problems.

It is now about 6 months since I first decided to have a stab at putting an Android app together after having my HTC Desire for a while. I am a professional developer but mainly on the Microsoft / .NET platform. Even so, the transition to Android, Java and Eclipse was not a smooth one...

Developing for Android

The initial hurdle was the general lack of good information and examples. Google have done an excellent job with their Android Developers site which will probably always be your first stop for information. But it for what is has in detail it lacks in examples.

Also, the nature of mobile development, particularly on the array of Android devices is complicated. Your web development skills will not help you here. Well maybe a tiny bit, but I wanted to sound dramatic.

I would also advise that you should be at the very least familiar with OOP and real-world programming methodologies if you want to start creating apps. This is not BASIC on your BBC Micro (showing my age there). If you're a seasoned Java developer who uses Eclipse on a Linux platform every day, then you have a huge advantage.

The Environment

Your choices for the IDE are the Eclipse or IntelliJ IDEA. Eclipse is by far the more widely used of the two and is also the one used in the Google guides, so this was my choice. However I have heard good things about IntelliJ so intend to check it out soon. I plan to do a whole post on setting up the environment later as there were some steps that I had trouble with even when following the Installing the SDK guide.

The Challenges

The Android platform is evolving rapidly and many of its strengths are also a headache for developers. Take the number of devices for example, great for Android, horrible for testing. Platform updates are also relatively regular with new features being added and old deprecated perhaps twice a year.

When you hit a problem and start searching you will often find examples using different approaches and sometimes raise more questions than answers; should you use the native Android methods?  Are they supported in all versions? Will the Java libraries do a better job? Or perhaps I need a third party library?
You can find a code example that is only year old but is completely out of date. 'Official' examples and best practices often do not exist. For the same reasons a good book only has a very short lifespan. This is very different from the .NET world.


It seems there are very few decent Android resources on the web. The most reliable have proven to be:
  • Google Developers - First stop for detailed information on objects and classes.
  • StackOverflow - A fantastic resource when you get stuck. Growing and helpful community, but be sure to search before you ask questions.
  • O'Reilly Programming Android - online book which is available for until it goes into publication. It's O'Reilly so expect content of the highest quality.

To keep ahead in the dynamic mobile environment you'll need to keep abreast of changes so you should follow (RSS or Twitter) some or all of the following:

Now it's time to take your first steps. Good luck...