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).
- Introduction to List Views Binding (this)
- Custom Row Model for List View
- Binding to Cursors
- Lazy Loading
In Android Binding, there are currently two types of object collection that can bind to ListViews (technically, AdapterViews). They are:
- ArrayListObservable – Which are collection of static Objects, and it has exactly same methods as ArrayList
- 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 =
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.