Recipe 3.3 Displaying Multiple ListViews

Android Versions
Level 1 and above
Permissions
None
Source Code to Download from Wrox.com
ListView2.zip

So far, the first two recipes in this chapter showed a single ListView in your activity; but it is common to have more than one ListView in an activity. This recipe demonstrates how to include multiple ListViews in your activity.

Solution

To display multiple ListViews in your activity, simply add multiple <ListView> elements to your UI, such as the activity_main.xml file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="List 1" />
    <ListView
        android:id="@+id/ListView1"
        android:layout_width="fill_parent"
        android:layout_height="200dp" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="List 2" />
    <ListView
        android:id="@+id/ListView2"
        android:layout_width="fill_parent"
        android:layout_height="200dp" />

</LinearLayout>

The preceding example contains two ListViews, each of which has a unique id: "@+id/ListView1" and "@+id/ListView2".

To fill each ListView with items, you need to get a reference to the ListView using the findViewById() method (see the following code). Once that is done, you can then bind it to an ArrayAdapter object:

package net.learn2develop.listview2; ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.