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 vast majority of .NET developers know very little about the Observer pattern; yet they use it with an unheard-of frequency every day. The Observer
pattern provides a widely accepted implementation for the recurring task of pushing notifications to listening components. In .NET, you don't need to learn
about this pattern because most common languages provide events. And just events are, under the hood, a hard-coded implementation of the Observer pattern.
In Java, you don't have events. This means that in Android development you need to learn about observers in order to respond to any user's activity. In this
article, we'll go through an Android application that accepts input from the user and handles user's clicking.
The User Interface
In the first article of this series I briefly mentioned XML files being used to define the template of the views. In this article, I'm not going to delve
deeper into this topic, but I'll definitely do that in the next one. For now, here's the full content of the XML file that defines the layout behind the
screen in Figure 1.
The layout uses resources like strings, images, and shapes. Shapes in particular are used to add gradients. Images and shapes are references
as drawable objects in a specific project folder. Here's Figure 1 to form an idea about the expected output.
Figure 1: The user interface of the sample application.

The screenshot on the left represents the default UI; the screenshot on the right
shows the state of the application after the user has tapped the yellow-bordered area. The sample application does just a couple of simple things. First, it
expects the user to type some text into the text box and then after the user taps the button the text is displayed below. Second, if the user taps the
yellow-bordered area an analog clock is displayed. Tapping again hides the clock. Let's see how to deal with such events.
Events in Android
As mentioned, event handling in Android follows the pattern in which events are handled in Java. What you know as an event handler in .NET languages is
known as a listener in Java. A listener is an object, however, and not simply a method or a delegate. Here are the listener instances for the button click
and label click of the sample application.
You should declare a private member in your activity class for each event handler you need. The Android SDK comes with a bunch of predefined
listeners mostly defined in the android.view.View namespace. Table 1 lists the most common of them.
Table 1: Listener classes available for a view.
Listener | Description |
OnClickListener | Handles the click event |
OnCreateContextMenuListener | Handles the creation of the context menu |
OnDragListener | Handles drag-and-drop operations |
OnFocusChangeListener | Handles the change of focus in a view |
OnLongClickListener | Handles the long click event, that is when the user clicks and holds for about a
second |
OnKeyListener | Handles keyboard events |
OnTouchListener | Handles touch events such as pinch-and-zoom and swipes. |
To be precise, a listener is a class that implements the interface through which the event listener and the event publisher can communicate. The
component that exposes the event is responsible for defining the interface through which it intends to notify the event. Components interested in
subscribing to the event just implement the interface and register with the publisher. This is the essence of the Observer pattern.
Mapping this
concept to the .NET world, we could say that the listener is a class that contains the event handler. The event handler logic is buried in a class that
implements a given interface instead of being expressed as plain code when not with an anonymous delegate. Let's take a second look at the sample listener
we considered a moment ago:
The member buttonWelcomeClickListener is expected to be an instance of a class that inherits from View.OnClickListener
and overrides the method OnClick. The method OnClick is the only member of the interface used to handle click events. The
code shown uses a more succinct (and fairly common) syntax - an anonymous class. An anonymous class is defined and instantiated in a single compact
expression. Looking at the code snippet, the only code you need in .NET to define the event handler is the method UpdateScreen.
The second step of
defining events is the subscription. This step has a close analogy with the .NET technique of adding handlers. The only difference is that .NET languages
offer a compact idiom typically represented by the += operator. In Java, you just call a method and pass it a reference to the expected
interface. To write your Android code in a clean way, you might want to attach handlers to any UI elements only once and in a unique place. You typically do
that in the onCreate method of the activity.
Here's a possible content for AddHandlers.
Analogous methods exist for other events.
Event Handlers
Most of the time, you use event handlers to update visual elements using the data entered in other visual elements. Here's a basic example of how to read
the content of a textbox and update a label.
The method getText returns the content of the specified EditText element. Note that getText doesn't directly return a string.
Instead, the method returns an Editable object. To extract the real text, you must add a call to toString. To set the content of an EditText or a TextView
you call the method setText and pass it a plain string.
When you have edit views, the system automatically displays a soft keyboard for
users to enter text. Depending on the UI layout, users could then be able to submit the text with the keyboard still visible. To make sure the keyboard is
dismissed when you start processing input, you might want to programmatically hide it. Here's how.
Toast Messages
In case of invalid input you might want to display a message to the user. In Android, you have classic message boxes but also a feature that personally I
like a lot - toast messages. The term toast message has different meaning in Windows Phone 7 and Android. In Windows Phone 7, it indicates a notification
message that an external system pushes to your phone. Such a notification message appears in the topmost bar of the screen. In Android, a toast message is
something different. It is a small view that can be centered in the screen. The toast can display any content, but it offers a very handy programming
interface for displaying just text messages. The nicest aspect of toast messages is that they disappear automatically after a few seconds. In a way, they
are the Android counterpart of timed message boxes. You have no such a feature in iPhone. Both in iPhone and Windows Phone creating a toast class isn't that
hard; having it out of the box, however, is just great.
You usually create a toast object at the beginning of your application and associate it with a
message and a timeout. Here's the code you need:
The context parameter indicates the parent of the view; the text parameter is the text to display; the third parameter indicates the number of
milliseconds you want the view to stay on. To display the toast you call the method show. You can use a single toast object for all of your messages. To
change the text, you use the method setText. The method setGravity can be used to determine the position where the toast will
display. The following code shows how to create a toast that displays centered vertically.
Figure 2 shows the toast in action.
Figure 2: The toast message in case of invalid input.

Hide and Display
The final feature we consider in this article is hiding and displaying visual elements. When you tap in the yellow-bordered area of the figure an analog
clock is displayed, as in Figure 1. Tapping again will toggle between the clock and the label. Here's the code for this:
Methods getVisibility and setVisibility allow you to get and set the visibility of visual elements. Constants VISIBLE,
INVISIBLE, and GONE can be used to indicate the desired status. INVISIBLE means the element is not displayed but
room for it is reserved in the layout. GONE, instead, indicates the element will be removed from the layout.
Summary
Event handling and UI updates are at the foundation of any mobile application. In this article I just covered basic events and very simple UI updates,
but it is definitely enough to show you the way ahead. Next time, I'll discuss how to make the UI more compelling with layouts, gradients, images and
menus.
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.
About Dino Esposito
 |
Dino Esposito is one of the world's authorities on Web technology and software architecture. Dino published an array of books, most of which are considered state-of-the-art in their respective areas. His most recent books are “Microsoft ® .NET: Architecting Applications for the Enterprise” and “...
This author has published 53 articles on DotNetSlackers. View other articles or the complete profile here.
|
You might also be interested in the following related blog posts
The Telerik CAB Enabling Kit and SCSF - Tutorial 5: The RadPanelBar UIExtensionSite
read more
Forcing event unsubscription
read more
Creating Objects with Observable Properties in JavaScript
read more
Event Aggregation with jQuery
read more
A Lightweight Event Framework in JavaScript
read more
Web.UI ASP.NET Grid: Synchronize Checkbox States with Row Selection
read more
Learning WPF at the WPF LOB tour and XAMLFest events
read more
ASP.NET MVC Controls and Good versus Evil
read more
ASP.NET Data Control Events
read more
The DefaultButton Property - News To Me!
read more
|
|
Please login to rate or to leave a comment.