Programming and Personal Development

Android ListView Part1

As the name suggests, ListViews are useful for displaying a scrollable list of items to the user. The items can be of any of the standard types like String or custom user defined types. It lets the users select one or more elements from the list and provides listeners to track change in selections.  But before we can go into the details  of the ListView and its usage, lets take a quick detour to learn about Adapters in Android.

Adapters

Adapters in android provide the input data and help generate the views for each item within the list.  In a abstract sense, they adapt data from disparate sources and provide a common interface for the view elements in Android such as ListViews and Spinners. Hence the name. Android comes with predefined Adapters such as an ArrayAdapter that wraps a Java collection of input items and Cursor adapter that fetches data from the Database,  among others. However you are certainly not restricted to predefined adapters and Android even provides a BaseAdapter class that can be extended for building custom adapters that adapt data from a completely different source such as a webservice. We will be using ArrayAdapters in our demo examples.

ListView and ListActivity

To create and display items in a list view, you need to :
  1. Declare the ListView element in the XML layout file.
  2. Source the layout in the Activity class using the setContentView  method
  3. Create a Adapter such as an ArrayAdapter to feed the input items to be listed
  4. Bind the adapter to the activity class using the setAdapter () method.
  5. Define the setItemClickListener () method to track the changes to the selections within the list
However you can skip a few of the above steps, if the main purpose of your activity is to display the list of items. You can

Demo output for Android ListView

Demo output for Android ListView

extend your activity from ListActivity class instead of the usual Activity class. ListActivity is a convenience class provided by android to simplify list handling and comes with a default layout that contains a ListView Element.  So if all  you want to do in your activity is to display the ListView items, then you can skip step2 altogether. But if you do want to customize your layout, you should declare your ListView element  with id ”@android:id/list” ( see example below).

You can bind the Adapter class with the activity using the setListAdapter method and define the listener by overriding the onListItemClick () method. This method gets called within the callback method provided by the ItemClickListener within the ListActivity class.

Example

In this demo example, we are going to create a simple Activity that extends ListActivity class. It contains a ListView element that lists a few strings and track the user selections on a TextView element as shown.
First, define the UI elements within a XML layout file.  Note that we have declared the id of the ListView element as ”@android:id/list”. This is required to for android to know which is the main list for the activity.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">
 
    <TextView android:id="@+id/listdemo_tv1"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:text=""
              android:gravity="center"/>
 
    <ListView android:id="@android:id/list"              android:choiceMode="multipleChoice"
              android:layout_width="match_parent"
              android:layout_height="match_parent"/>
</LinearLayout>
Second, declare a string array element within the resvaluestrings.xml in the project directory.  Its recommended to declare any Strings used in your project in the Strings.xml file as it makes it easy to adapt your strings later based on the locale of your app.
<string-array name="dev_platforms">
    <item>Android</item>
    <item>Iphone</item>
    <item>Windows</item>
    <item>Bada</item>
    <item>WebOS</item>
</string-array>

Finally, define the Activity class in the Java.
public class ListViewDemo extends ListActivity { 
    private TextView m_clickTracker;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listdemo);        m_clickTracker = (TextView) findViewById(R.id.listdemo_tv1);
        String[] platforms = getResources().getStringArray(R.array.dev_platforms);        ListAdapter listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, platforms);        setListAdapter(listAdapter);    }
 
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {        StringBuilder text = new StringBuilder(m_clickTracker.getText());
        if (text.length() > 0) {
            text.append(", ");
        }
        TextView tv = (TextView) v;
        text.append(tv.getText());
        m_clickTracker.setText(text.toString());
    }
}

  • Our ListViewDemo extends from ListActivity class
  • setContentView () method is used to source the layout within the Activity. This is done because  we have customized the layout with a TextView element to track user selections. If our layout were to say, just contain the ListView element, we can skip this step.
  • We use the getResources ()  method that is available within the Activity to get hold of the string array that we declared above and pass it as input to the ArrayAdapter class. This version of the ArrayAdapter’s constructor takes the following arguments:
    • Context that provides access to environment data like local files, databases, system services etc. This is usually the Activity itself.
    • Layout file that represents a TextView element. By default, the ArrayAdapter converts the items within, into a String object ( using toString () ) and wraps it with the layout specified. This layout controls the appearance of the list elements on the screen. In this case we use one of the predefined layouts,  android.R.layout.simple_list_item_1 which represents a singe line TextView element. Android allows us to provide our own layouts to customize the look and feel.
    • The input list of items, in this case our string array.
  • Call the setListAdapter () method to bind the Adapter to the ListActivity.
  • Define the action to take when the user clicks on a item in the list by overriding the onListItemClick() method. The ListView itself , the view, position  and the id of the element that was clicked are available as arguments to this callback method.  We cast the view that was passed into a TextView element, grab its text and append it to the clickTracker which is nothing but the TextView element that we defined in the xml layout file.
Note that this is the Model-View-Controller pattern in action. The ArrayAdapter supplies the underlying data ( Model) for the ListView (view) and the activity (the controller) communicates any changes to the underlying data (the user interaction) to the View which gets re-drawn.
Web Analytics