You are here

Android - List Basics

Submitted by admin on Wed, 05/29/2013 - 13:21

For Android, the contents of a list are managed in a view named ListView. For the fishing spot example, I'll create a view controller that has a LinearLayout as the top view. I'll then create an XML layout named location_list_view.xml. The contents of the layout file are as follows:

<?xmlversion="1.0"encoding="utf-8"?>

<LinearLayout

xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

<ListView

android:id="@+id/locationList"

android:layout_width="match_parent"

android:layout_height="wrap_content">

</ListView>

</LinearLayout>

This view is fairly straightforward: The top-level view is a linear layout, and it contains a single sub-view: an instance of ListView identified as locationList.

Note: Unlike iOS, I don't have a toolbar in this view controller. Why? Because Android provides a drop-down menu on every view, so I'll include my navigation controls in the menu.

Line 7: Android provides a helper class for managing the contents of a list - ArrayAdapter. Here, I've indicated that the array adapter will manage a collection of FishingSpot objects.

Lines 13 - 20: Public helper functions for setting / clearing the contents of the list.

Lines 26 - 28: Locate the ListView object, and associate it with a new array adapter. This must be done after the view had been inflated. (If you attempt to do this in the constructor, the list view will not be found.)

Line 27: This item merits extra attention. By specifying a base view of android.R.layout.simple_list_item_1, I'm stating that each row of the list will be a simple text label.

To add support for switching views, I've updated the main menu (activity_main.xml) as follows:

<menuxmlns:android="http://schemas.android.com/apk/res/android">

<item

android:id="@+id/menu_logout"

android:orderInCategory="100"

android:showAsAction="never"

android:title="@string/menu_logout"/>

<item

android:id="@+id/menu_show_list"

android:orderInCategory="101"

android:showAsAction="never"

android:title="@string/menu_show_list"/>

<item

android:id="@+id/menu_show_map"

android:orderInCategory="102"

android:showAsAction="never"

android:title="@string/menu_show_map"/>

</menu>

In practice, I should have two separate menus: One for when the map view is displayed, and the other for when the list view is displayed. But for simplicity purposes, I've included both menu items on this single menu.