Thursday, January 30, 2014

ListView Basics for Android (using an ArrayAdapter)

Lists of repeating items are fundamental to almost any computer application and date back to the earliest days of programming.  It's difficult to think of an application that won't require them at some point, so it's usually one of the first things to tackle when learning to develop for any new operating system.

In Android, a list of scrollable rows is called a ListView.  To function, the ListView needs a ListAdapter which is a class that will format a view for each row from the desired data when called for by the activity which is controlling the ListView.

The ListAdapter can be one of the following types:
  • ArrayAdapter - Binds to an array of strings
  • CustomAdapter - Binds to a list of objects
  • CursorAdapter - Binds to an SQLite query
The simplest approach to display a list of items is to use the built-in ListActivity class.  It will already contain a ListView which fills the entire screen, and a ListAdapter to bind the data.  No AXML layout is required to define the screen layout.  Using an ArrayAdapter is all that is necessary to get simple data onto the screen.

using System; 
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace BlogPostListActivity
{
    [Activity (Label = "BlogPostListActivity", MainLauncher = true)]
    

    //Inherit from the ready made ListActivity Class for simplicity

    public class MainActivity : ListActivity
    {
        private string[] items;

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            //create a list of names to display
            items = new string[] {
                "Anita Drink",
                "Amanda Reconwith",
                "Warren Peace",
                "Rhonda Corner",
                "Karen Feeding",
                "Rufus Lee King",
                "Winston Payne",
                "Marian Haste",
                "Augusta Wind",
                "Eileen Dover",
                "Wendy Lottery",
                "Betty Wont",
                "Marty Graw"
            };

            // Set the built-in ListAdapter to a new instance of an ArrayAdapter
            // Set the layout to the pre-defined SimpleListItem1 

           //  and pass it a reference to this activity and the items array
            ListAdapter = 

               new ArrayAdapter<String> 
                           (this, Android.Resource.Layout.SimpleListItem1, items);

        }
    }
}


Nothing further is need to display the array data.




No comments:

Post a Comment