Android for .NET Developers - Building the User Interface

Published: 5/4/2011
By: Dino Esposito

In this article, you will learn how to build the user interface.

Contents [hide]

The Android for .NET Developers Series

  • Part 1 Starting with this article, I'll discuss what you need to know to approach Android programming without any aid from your .NET expertise.
  • Part 2 In this article, we'll go through an Android application that accepts input from the user and handles user's clicking.
  • Part 3 In this article, you will learn how to build the user interface.
  • Part 4 In this article, I'll be delving deep into menus and dialog boxes in Android for .NET, and discuss a few very common (and frequently used) types of menus and dialogs.
  • Part 5 In this article, Dino Esposito focuses on the options that the Android SDK offers for local storage.
  • Part 6 In this article, Dino Esposito shows how to build settings dialog boxes using a built-in feature of Android for .NET.
  • Part 7 In this article, I'll dissect the code of a realistic application - a waterpolo score manager - to show how to save and resume the status of a game using both the internal storage and SD card.
  • Part 8 In this article, I'll focus on the execution of common tasks from within an Android application. I'll build the skeleton of an application that takes a photo and emails to the specified address. For both tasks I'll use native Android components.
  • Part 9 In this article, I'll discuss how to arrange an Android view where the dominant element is the list. I'll start with a plain list of strings and then improve up to populating a listview with downloaded content arranged using a custom layout.
  • Part 10 In this article, I'll discuss the features and capabilities required by an Android application to talk with Twitter. In particular, I'll focus on authentication and updates.
  • Introduction

    The user interface of native mobile applications often relies on a new family of widgets that do not exist - at least not in the same form - in Web and desktop user interfaces. Rounded panels, data tables, pick lists are fairly common, but I'd also call your attention on the use of bitmaps, icons and gradients that are probably more common than in other types of application.

    Any Android project contains a folder of resources and resources are catalogued in subfolders by category - menu, layout, values, drawable. (See Figure 1.) You populate these folders with a bunch of files representing various visuals. In this article, I'll go through a bunch of topics that revolve around the use of resources and illustrate how to accomplish some common tasks such as displaying an image, a rounded panel, localized strings, menus, and modal dialogs. I'll start with the first type of resource you deal with even when your goal is simply writing a hello-world application - the layout resource.

    Figure 1: Resources in an Android project.

    Resources in an Android project.

    Layouts

    In Android, the term layout indicates the structure of any content displayed in a view. You can define the content being displayed in a view either programmatically or declaratively. In the former case, you build the visual tree by creating instances of widgets and adding them to the root element of the view. In the latter case, you provide an XML-based description of the expected user interface and have the activity (the primary type of Android component) to parse it and figure out the widgets to create. The following code shows how to populate the user interface of an activity with a layout loaded from the resources of the application.

    The setContentView method takes either the ID of a layout resource or a programmatically created View object. If the method is passed the ID of a layout resource then it parses the content and builds widgets. If the method is passed a View object then it just adds the view to the list of child widgets. The code below demonstrates how you can create widgets and add them programmatically to an existing view.

    You first get the main view from a layout and then create a label of text (a TextView object) and add it to the content of the view. It goes without saying that you can still call addContentView even if you didn't call setContentView beforehand. All you get in this case is a relatively empty template in which all that appears is what you explicitly added through code. Note, though, that in case you're creating a layout from scratch you should start with a layout object such as LinearLayout. You're not allowed to have a TextView or a Button as the root of the view. To add widgets programmatically at a specific point of an existing hierarchy, you must first locate the parent object and then add the view to its subtree, as below:

    In Android you have four main types of layouts: FrameLayout, LinearLayout, TableLayout and RelativeLayout.

    An extremely simple container, FrameLayout is basically a placeholder for a single object. Ideally, you use it to reserve a blank space in your main layout where some dynamic content will be displayed. The content of the FrameLayout is a single object but with any level of nesting you like. All child objects of a FrameLayout are always rendered from the top-left corner of the screen.

    LinearLayout is a frequently used layout that like the StackPanel in XAML stacks its child elements either horizontally or vertically. An interesting capability of the LinearLayout object is support for weight. Weight is an integer meant to indicate the importance of a child element and is set to 0 by default. A higher weight value provides a hint for the activity which will try to stretch weighed elements to a larger size.

    TableLayout looks like a HTML table but it doesn't feature most of the advanced capabilities of HTML tables. In particular, it doesn't support graphics such as borders or padding and only supports rows. Columns are calculated based on the maximum number of cells required by a single row. Cells in a row are not allowed to span over multiple columns.

    The RelativeLayout is a container in which contained elements indicate their preferred position relative to the parent. Likewise, a child object can specify its position relative to another element identified by ID. As an example, you can align two objects to the right edge or place one under the other, center elements and so forth.

    The most common way of creating user interface in Android is through XML layout files. Overall, the XML language used to define layouts is not much different from the XAML schema you use in Silverlight and Windows Phone 7 (WP7) applications. More precisely, the similarity is more functional than syntactical and the Android XML is anyway a small subset of the WP7 XAML. As a .NET developer with some familiarity with XAML, however, you'll feel quite comfortable and have a smooth approach to layout in Android.

    Finally, layouts are not the only root containers you can have. More specialized and specific containers exist such as Tab for tabbed views, ListView for rich list-based views and GridView which offers instead a cell-based view similar to Grid in XAML.

    When defining a layout, you must provide at least width and height. The code below shows an example.

    The orientation setting is as much important to set but at least it has a default value - horizontal. If you miss layout_width and layout_height you get a runtime error. Note, however, that the IntelliJ IDE catches that and gives you a warning in the editor.

    Drawable Resources

    Writing Android applications may be problematic because of the fairly fragmented set of devices capabilities. As an operating system, Android can in fact run on a variety of devices with different screen sizes and resolutions. In an effort of reducing the workload for developers, Android defines four categories of a size: small, normal, large, and extra-large. The extra-large size has been added only with Android 2.3. How does this affect you?

    In Figure 1 you see three size-related subdirectories under the res folder: drawable-hdpi, drawable-mdpi, and drawable-ldpi. The specific project in Figure 1 is for Android 2.2; that's why the fourth size is missing. The drawable-xxx folders contain drawable resources for the various screen densities - low, medium, large and extra-large. Examples of drawable resource are images, gradients and shapes to be used as the background of layouts. The layout folder (see Figure 1) contains the density-agnostic layouts. If you want to make available different layouts for the various densities, then add layout-xxx folders under the folder res. In this case, though, xxx stands for small, large, large-land and xlarge. The string large-land stands for large density in landscape mode. Layouts for the normal density are stored in the layout folder.

    To minimize the burden of supporting a myriad of different devices, you are strongly encouraged to express sizes using density-independent pixels or dip. In this case, the real estate really processed by the system is based on a measure that takes into account resolution and actual screen size.

    Let's see a few examples of drawable resources starting with a shape. You use a shape to define a combination of graphical entities to render as the background of layouts. The following code shows a shape that simply contains a gradient. Let's assume the code is taken from a file named apptitlebar.xml located in a drawable-xxx folder.

    The shape is a rectangle and contains a blue-ish gradient. To give an area of the screen this background, you proceed as follows:

    The background attribute references a drawable resource named apptitlebar. The name of the resource must match the name of a file in one of the drawable-xxx folders. Here's an example of a slightly more sophisticated shape with a rounded rectangle, padded, with a border and a gradient in the background.

    You reference images in a similar manner. You use the ImageView object as a container and make it point to a resource in a drawable folder.

    In the preceding example, titleicon references an image file - mostly, but not necessarily a PNG file.

    Style and Themes

    Multiple graphic attributes can be grouped together into a style. The overall developer experience is analogous to styles as you may know them from XAML. Here's how you style an element:

    In this case, CoolButton is a style defined in a XML file located in the res/values folder of the project. The name of the XML file doesn't matter.

    A style can be inherited from an existing style. If the parent style is a system style, you use the parent attribute on the style element, as shown below:

    If you want to inherit from one of your styles then you use a slightly different syntax similar to the CSS syntax. The name of the style results from the concatenation of the parent style with derived style. For example, you can have CoolButton.Shadowed where both are user-defined styles defined within the same application.

    An Android style can be used to style individual elements as well as an entire application. If you want to style an entire application, then you use the theme attribute to reference the style by name in the application tag within the android manifest file.

    Summary

    An aspect of Android programming that scares many developers is the variety of devices that an application can be used on. The issue can be smoothed but not eliminated. Density independent measures and specific layout for categories of screen devices provide a good starting point. Beyond that, an Android user interface can be defined in much the same way you do with XAML in Silverlight and Windows Phone applications. The syntax is not certainly the same, but an overall similarity between the XML schema of Android and XAML cannot be denied. If you're familiar with stack panels and other XAML amenities such as styles and resources you'll find a matching element pretty soon in Android as well. Building an Android interface is not that hard except for the lack of visual designers. In this regard, for Android you can use DroidDraw as a designer as available from http://droiddraw.org.

    The Android for .NET Developers Series

  • Part 1 Starting with this article, I'll discuss what you need to know to approach Android programming without any aid from your .NET expertise.
  • Part 2 In this article, we'll go through an Android application that accepts input from the user and handles user's clicking.
  • Part 3 In this article, you will learn how to build the user interface.
  • Part 4 In this article, I'll be delving deep into menus and dialog boxes in Android for .NET, and discuss a few very common (and frequently used) types of menus and dialogs.
  • Part 5 In this article, Dino Esposito focuses on the options that the Android SDK offers for local storage.
  • Part 6 In this article, Dino Esposito shows how to build settings dialog boxes using a built-in feature of Android for .NET.
  • Part 7 In this article, I'll dissect the code of a realistic application - a waterpolo score manager - to show how to save and resume the status of a game using both the internal storage and SD card.
  • Part 8 In this article, I'll focus on the execution of common tasks from within an Android application. I'll build the skeleton of an application that takes a photo and emails to the specified address. For both tasks I'll use native Android components.
  • Part 9 In this article, I'll discuss how to arrange an Android view where the dominant element is the list. I'll start with a plain list of strings and then improve up to populating a listview with downloaded content arranged using a custom layout.
  • Part 10 In this article, I'll discuss the features and capabilities required by an Android application to talk with Twitter. In particular, I'll focus on authentication and updates.
  • Please visit the link at the below url for any additional user comments.

    Original Url: http://dotnetslackers.com/articles/net/Android-for-NET-Developers-Building-the-User-Interface.aspx