List view is one of the most commonly used widget in Android, but very often, getting data to display in List is a painful task. Most of the time, you need to code your own Adapters (and those SimpleAdapter ain’t really useful in many situation).

Codes in this tutorial series are modified from the AndroidBindingMarkupDemo, under section Simple List. Source code of the markup demo is available here.

Series Directory:

  1. Introduction to List Views Binding (this)
  2. Custom Row Model for List View
  3. Binding to Cursors
  4. Lazy Loading

In Android Binding, there are currently two types of object collection that can bind to ListViews (technically, AdapterViews). They are:

  1. ArrayListObservable – Which are collection of static Objects, and it has exactly same methods as ArrayList
  2. CursorCollection – Which are mapped to Cursor Rows, one of the most important concept in Android.

Both of the above two classes are sub-class of ObservableCollection, you may create a HashtableObservable by extending ObservableCollection and still bindable to views.

We first look at ArrayListObservable as Data source.

public final ArrayListObservable<String> Items =
new ArrayListObservable<String>(String.class);

Above declared a Array List of type String. Simple, right? We don’t need to bother to program an adapter to tell how to display this, everything related to display logic should (ideally) placed in the XML file, so, let’s look at the XML layout file (only the ListView is shown for clarity):

<ListView
android:id="@+id/lvItems"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
binding:itemSource="Items"
binding:itemTemplate="@layout/arraylist_item"
/>

There are two custom tags appeared in the above XML. itemSource is the data collection that the ListView should display, and itemTemplate is a reference to other layout id. Let’s take a look at the template (@layout/arraylist_item):

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:binding="http://www.gueei.com/android-binding/"
android:id="@android:id/text1"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:paddingLeft="6dip"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center_vertical"
binding:text="."
/>

The above piece of XML is working exactly as main layout XML, only the context of all the bindings are within the individual item. We bind the TextView’s Text with a “.” that means the object itself. Since our list is currently a list of String, so binding to itself means displaying the String’s content.

About these ads