Pages

Monday, 13 June 2011

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:

/res/layout/prefs.xml
Preferences screen
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    android:title="Preferences">

  <PreferenceCategory
     android:title="Options">

     <CheckBoxPreference
       android:key="pref_opt1"
       android:title="Option 1"
       android:summary="Tick to set this option"
       android:defaultValue="true"
       />
    <CheckBoxPreference
       android:key="pref_opt2"
       android:title="Option 2"
       android:summary="Tick to set this option"
       android:defaultValue="true"
       />
  </PreferenceCategory>

  <PreferenceCategory
     android:title="Selection">
      
    <ListPreference
        android:key="pref_type"
        android:title="Type"
        android:summary="Select item from array"
        android:entries="@array/types"
        android:entryValues="@array/types_values"
        android:defaultValue="1"
        />

    <EditTextPreference
        android:key="pref_text"
        android:title="Input text"
        android:summary="Tap to enter some text"
        android:dialogTitle="Enter text"
    />
     
  </PreferenceCategory>

  <Preference
    android:title="Intent"
    android:summary="Open a webpage">

    <intent
      android:action="android.intent.action.VIEW"
      android:data="http://android-elements.blogspot.com/" />

  </Preference>
   
</PreferenceScreen>

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:

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

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


src/your.package.name/Prefs.java
package com.example.com;

import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Prefs extends PreferenceActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.layout.prefs);
    }   
}

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);
          editor.commit();        
    }
     
    // 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);
          editor.commit();        
    }

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:

AndroidManifest.xml
<application
  android:icon="@drawable/icon"
  android:label="@string/app_name"     
  android:theme="@android:style/Theme.NoTitleBar"
  <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.

/res/values/themes.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <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>
  </style>
</resources>

/res/values/styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="windowTitleBackgroundStyle">  
    <item name="android:background">@FF000</item>                
  </style>
  <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>
  </style>
</resources>

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

AndroidManifest.xml
<application
  android:icon="@drawable/icon"
  android:label="@string/app_name"     
  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:
<application
  android:icon="@drawable/ic_launcher"
  android:label="@string/app_name"
  android:theme="@android:style/Theme.Light">
  <activity
    android:name=".Main"
    android:theme="@android:style/Theme.Light.NoTitleBar">

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:

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

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

Manfiest sample:
...
<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/Theme.myTheme">
    ...

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:

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

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:

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

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="My styled text view"
        style="@styles/myWarning" />
</LinearLayout>

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,