Android for .NET Developers - Picklists and Listviews

Published: 12/26/2011
By: Dino Esposito

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.

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.
  • Introduction

    Long lists of items are not so common in web applications because displaying too many items on a single web page would make the page slower to download. In addition, displaying too many items within a page would force the user to deal with the scrollbar which may not be fun. So developers looked into pagination and pager bars became a common presence on any web page with more than twenty items to display.

    In mobile applications, pagination is not necessarily a big deal for a couple of reasons. First, scrolling is a very natural gesture on touch-based whether tablets or handheld devices. Second, native mobile applications rely on a richer software infrastructure than most web sites so they can leverage data caching and REST services returning data-only responses instead of HTML-based responses. In this way, the payloads are much smaller and the download time is not necessarily an issue. Furthermore, any downloads happen asynchronously which makes the user experience much smoother anyway.

    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.

    The ListActivity Class

    In Android you use the ListView widget to display a list of items. The ListView widget is a standard user interface component that you compose with other UI elements in a layout file. For a .NET audience, it should be noted that the Android ListView is more similar to a custom-draw listbox than to a multi-column listview control. More often than not when you have a list in the user interface you also need some additional services such as data binding and item clicking. These services must be coded over and over again unless you work this code out to a reusable component.

    In Android, this is precisely the role played by the ListActivity class. The ListActivity class extends the base Activity class with some extra features such as a built-in logic to handle the click on a displayed item. In Android, you need a data adapter component in order to perform data binding. The ListActivity comes with a base ListAdapter class and with a basic layout for displayed elements. In the end, the minimal code you need to displayed a list of items is shown below:

    Where's the ListView to be populated? The ListActivity class requires that the application's main layout contains a ListView widget with a specific ID. Here's an excerpt from the layout file:

    The layout file is not limited to contain just a ListView with a fixed ID but it can contain any other widgets; as long as the layout contains a ListView named list the activity works just fine.

    The ListAdapter class is the base adapter class for lists of data. In Android an adapter is the engine that performs data binding. The adapter, in fact, is responsible for retrieving the data to list and for the actual binding of data items to list items. A ListView usually works with either of two built-in adapters-the array adapter and the cursor adapter. As the name suggests, the array adapter is a collection of homogeneous data whether strings or complex types. The cursor adapter is designed to move sequentially over a block of data returned by a database query. Here's some sample code that creates and assigns an array adapter:

    The adapter receives the data to display as an array and uses the built-in layout resource to arrange a view. The simple_list_item_1 ID refers to a basic template that just displays the text of array element with a default font and default style. This layout is predefined. Finally, the setListAdapter method binds the adapter to a ListView named list in the activity's layout.

    Handling the Item Clicking

    As you may know, detecting the click on an Android user interface element is not as immediate and quick as it is in .NET. You need to create a view listener class, override the click event with your handler code and then register the listener with the widget. For a listview, this boring task should be repeated for each bound data item. The ListActivity class saves you from most of this work and only requires that you indicate the code to execute after an item is clicked.

    The ListActivity class feature an overridable method named onListItemClick with the prototype shown below. By simply overriding this method you define the code that will run after an item click.

    The list adapter offers the getItem method through which you can programmatically retrieve the current data item out of the list.

    Customizing the Layout

    Employing a user-defined layout for a list item can be a trivial task if all that you want is just adjusting some graphics and perhaps add a static bitmap. In this case, all you do is defining a new layout file, say listitem.xml, and pass it to the adapter.

    As you may have noticed, the array adapter now takes an additional parameter-R.id.text. That is the ID of the element in the list item layout that will accept the bound text. A custom layout can be defined as below:

    The ImageView element named icon will reference a fixed image; the TextView element named text will display the bound text.

    Frankly, this is not really a realistic scenario; if you decide to change the listview layout you probably want to be able to more deeply alter it and especially based on runtime conditions and special values of the bound text. For this, you also need a custom adapter.

    Building a Custom List Adapter

    A custom list adapter is essentially a class that inherits from ListAdapter or from an existing adapter (e.g., ArrayAdapter) and overrides the getView method. The getView method is where the adapter populates the user interface of the ListView widget. Here's an example that shows how to effectively implement the getView method and display a different icon based on the content of the bound item.

    It should be noted that the previous code is heavily inspired by examples in the Android SDK so it can be considered a best practice for building custom adapters for list views. Let's explore it further.

    All that the method getView has to do is returning a View object for the item being displayed. However, to save resources Android provides an internal mechanism to reuse View objects instead of creating new ones every time. So the parameter convertView that gets passed to your adapter references the old view (if any) you can reuse. The first time the parameter is null and all that you can do is creating a new View object from scratch. Next time, you'll receive a non-null View object and just modify its elements without having to create it from scratch.

    To bind data to a list item view, you need to retrieve a reference to the various elements that populate a list item layout. You can do that via findViewById. Because calling the findViewById function is expensive you can cache the references on the view object itself. You use a ViewHolder custom class to store references to any programmable element you have in the list item layout. In the preceding code, we only have an ImageView and a TextView. You use the setTag method to associate this extra data to the View being used by the Android ListView widget.

    When the convertView parameter is not null, you don't need to create a new View object and also don't need to retrieve references to layout elements as they are now stored in the tag of the object. You retrieve the helper object that contains references as below:

    The final step consists in binding data to the TextView of the row layout and choosing the icon to display. Because the example lists a few tennis matches (let's say that the source of this information is live score web service) you can use a different icon whether the match is in progress or is completed. Figure 1 shows a screenshot of the application up and running.

    Figure 1: A listview with a custom layout.

    A listview with a custom layout.

    Summary

    ListViews are common in mobile applications, and Android applications are no exception. Lists are easy to scroll and can be populated asynchronously. However, most of the data that you might want to show in a list come from the Internet. Mobile applications should be very careful about connectivity as connectivity is an asset that easily comes and goes. For this reason, an adapter should also be smart enough to cache data and reuse the latest download when no connectivity is present. But this makes just good fodder for another article.

    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.
  • Please visit the link at the below url for any additional user comments.

    Original Url: http://dotnetslackers.com/articles/net/Android-for-NET-Developers-Picklists-and-listviews.aspx