Click here to Skip to main content
Click here to Skip to main content
Go to top

Android Custom List Adapter in MonoDevelop (Mono for Android C#)

, 3 Aug 2012
Rate this:
Please Sign up or sign in to vote.
Some of the Android SDK’s built-in layouts for ListView items, classes for creating list adapters, and ListActivity for displaying a ListView.
Custom List Adapter

Output Image

Data Adapter

A data adapter is the channel by which data is bound and passed to user interface controls. The core function of a data adapter is to grab a requested data entity, bind it to the appropriate view item, and pass that view to the adapter view.

Adapter View

An adapter view is a special type of viewgroup. As with other viewgroup types, its main purpose is to be a view that contains child views. As such, adapter views determine the presentation of the layout of its child views.

Native Adapters

The Android runtime has several native adapters that cover a wide variety of different use cases. In this example we are using BaseAdapter. This is the adapter’s common abstract class. It provides the framework for some native adapters, such as ListAdapter and SpinnerAdapter. In addition, this is a great place to start when considering creating your own custom adapter.

Creating a Custom List Adapter

By inheriting from the BaseAdapter class, we have to override several methods to allow proper functionality of the adapter. Methods are methods, Count(), GetItemId(), and GetView(). You can have your own layout for your ListView items that use your own custom list adapter subclassing the BaseAdapter class. The example uses a list of Product objects as the data source. Create a class Product file named Product.cs.

Create New Android Application solution in the MonoDevelop development tool.

Solution Image

  1. Right click on project--->Add new file-->Android class (Product.cs).
  2. namespace ListAdapterDemo
    {
        public class Product
        {
            public string Category {
                get;
                set;
            }
    
            public string Name {
                get;
                set;
            }
    
            public string Description {
                get;
                set;
            }
    
            public int Image {
                get;
                set;
            }
        }
    }

    Next, a layout is needed for each ListView item. A ListView item usually displays information for a single object from your data source. A single ListView item is responsible for displaying information for a single product, including the name, description, and image.

    A horizontal LinearLayout holds an ImageView for the product’s image, and a child vertical LinearLayout holds two TextViews: one for the product’s name, and another for the product’s description. This layout causes the image to appear on the left. To the right of the image are the name and, under that, the description.

    ListView item layout for Product
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="80px">
        <ImageView
            android:id="@+id/imageItem"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical" />
        <LinearLayout
            android:id="@+id/linearText"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:orientation="vertical"
            android:layout_marginLeft="10px"
            android:layout_marginTop="10px">
            <TextView
                android:id="@+id/textTop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="TextView" />
            <TextView
                android:id="@+id/textBottom"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="TextView" />
        </LinearLayout>
    </LinearLayout>
  3. Open-->Resources--->Layout-->Main Layout
  4. Replace above XML in main layout and rebuild. Note the IDs of the various views inside your layout for which you will want to set the data programmatically. In this case, you should take note of the IDs for the ImageView as well as both of the TextViews: imageItem, textTop, and textBottom. Mono for Android automatically makes these IDs available to you for referencing in the Resource.Id class.

  5. Right click on project--->Add new file-->Android class (ProductListAdapter.cs).
  6. namespace ListAdapterDemo
    {
        class ProductListAdapter:BaseAdapter<Product>
        {
            Activity context;
            public List<Product> listProducts;
    
            public ProductListAdapter (Activity context, List<Product> lProducts): base()
            {
                this.context = context;
                this.listProducts = lProducts;
            }
    
            public override int Count {
                get { return this.listProducts.Count; }
            }
    
            public override Product this [int position] {
                get { return this.listProducts [position]; }
            }
    
            public override View GetView (int position, View convertView, ViewGroup parent)
            {
                var item = this.listProducts [position];
                var view = convertView;
                if (convertView == null || !(convertView is LinearLayout))
                    view = context.LayoutInflater.Inflate (Resource.Layout.Main, parent, false);
                var imageItem = view.FindViewById (Resource.Id.imageItem) as ImageView;
                var textTop = view.FindViewById (Resource.Id.textTop) as TextView;
                var textBottom = view.FindViewById (Resource.Id.textBottom) as TextView;
                imageItem.SetImageResource (item.Image);
                textTop.SetText (item.Name, TextView.BufferType.Normal);
                textBottom.SetText (item.Description, TextView.BufferType.Normal);
                return view;
            }
    
            public override long GetItemId (int position)
            {
                return position;
            }
        }
    }

    The adapter needs a reference to a context so that the layout and all the views within it can be created for the ListView items. Any time you create view objects, a context is required, so this is no exception. Typically you would pass into the constructor a reference to the Activity that is creating the custom ListAdapter. The GetView method in the list adapter is responsible for returning a View that is the layout for a ListView item for the given position.

  7. Now open file Activity1.cs and change base class Activity to ListActivity.
  8. namespace ListAdapterDemo
    {
        [Activity (Label = "List Adapter", MainLauncher = true)]
        public class Activity1 : ListActivity
        {
            protected override void OnCreate (Bundle bundle)
            {
                base.OnCreate (bundle);
                CreateListData();
            }
            public void CreateListData ()
            {
                this.ListAdapter = new ProductListAdapter (this, 
                new List<product> () {
                new Product() { Category="Animals", Name = "Dog",
                    Description = "Dogs are great pets; they are more superior to any other pet. Dogs " + 
                    "are friendly, loyal house pets; these characteristics make a dog a great companions",
                    Image = Resource.Drawable.animal_dog },
                new Product() { Category="Animals", Name = "Elephant",Description = 
                    "I would want a pet elephant. I would want an elephant because " + 
                    "they are kind, big and cute animals.",Image = Resource.Drawable.animal_elephant },
                new Product() { Category="Animals", Name = "Turtle",Description = 
                    "Pet turtles, reptiles, fish, and shrimp are wonderful pets to have. " + 
                    "The vast number of these species require specialized care and equipment, " + 
                    "such as a turtle tank. Pet Turtles And More aims to share the love of " + 
                    "caring for these pets and other animals through videos, turtle pictures, and more",
                    Image = Resource.Drawable.animal_turtle },
                new Product() { Category="Cartoons", Name = "Mickey Mouse",Description = 
                    "Mickey Mouse is a cartoon character created in 1928 by Walt Disney and " + 
                    "Ub Iwerks at The Walt Disney Studio.[3] Mickey is an anthropomorphic mouse 
                    and typically wears red shorts, large yellow shoes, and white gloves",
                    Image = Resource.Drawable.cartoon_mickeymouse },
                new Product() { Category="Cartoons", Name = "Pooh",Description = "Disney's daughters " + 
                    "were also big fans of the wonderful Pooh-books. Remembering how much they enjoyed " + 
                    "these characters, Walt Disney was inspired to share them with the children around the world.",
                    Image = Resource.Drawable.cartoon_pooh },
                new Product() { Category="Cartoons", Name = "Pumbaa",Description = "This cartoon series " + 
                    "is based on the popular Lion King movie. Pumbaa's general knowledge " + 
                    "actually overshadows his.",Image = Resource.Drawable.cartoon_pumbaa },
                new Product() { Category="Cartoons", Name = "Tarzan",Description = "The jungle; here " + 
                    "I was born; and here my parents died when I was but an infant. I would have soon " + 
                    "perished, too, had I not been found by a kindly she-ape named Kala, who adopted " + 
                    "me as her own and taught me the ways of the wild. I learned quickly, and grew " + 
                    "stronger each day, and now I share the friendship and trust of all jungle animals.",
                    Image = Resource.Drawable.cartoon_tarzan },
                new Product() { Category="Cartoons", Name = "Timon",Description = "This cartoon " + 
                    "series is based on the popular Lion King movie. The sidekicks of the movie, " + 
                    "a meerkat named Timon and a warthog named Pumbaa are the main characters of the series.",
                    Image = Resource.Drawable.cartoon_timon },
                new Product() { Category="Flowers", Name = "Pollen",Description = "Many flowers " + 
                    "have evolved to be attractive to animals, so as to cause them to be vectors " + 
                    "for the transfer of pollen.",Image = Resource.Drawable.flower_pollen },
                new Product() { Category="Flowers", Name = "Rose",Description = "A rose is a woody " + 
                    "perennial of the genus Rosa, within the family Rosaceae. There are over 100 species. " + 
                    "They form a group of erect shrubs, and climbing or trailing plants, with stems " + 
                    "that are often armed with sharp prickles.",Image = Resource.Drawable.flower_rose },
                new Product() { Category="Fruits", Name = "Apple",Description = "The apple is the " + 
                    "pomaceous fruit of the apple tree, species Malus domestica in the rose family " + 
                    "(Rosaceae). It is one of the most widely cultivated tree fruits, and the most widely " + 
                    "known of the many members of genus Malus that are used by humans. Apples grow " + 
                    "on small, deciduous trees.",Image = Resource.Drawable.fruit_apple },
                new Product() { Category="Fruits", Name = "Banana",Description = "Banana is also used " + 
                    "to describe Enset and Fe'i bananas, neither of which belong to the aforementioned " + 
                    "species. Enset bananas belong to the genus Ensete while the taxonomy of Fe'i-type " + 
                    "cultivars is uncertain",Image = Resource.Drawable.fruit_banana },
                new Product() { Category="Fruits", Name = "Strawberry",Description = "Strawberry cultivars " + 
                    "vary widely in size, color, flavor, shape, degree of fertility, season of ripening, " + 
                    "liability to disease and constitution of plant.[6] Some vary in foliage, and some " + 
                    "vary materially in the relative development of their sexual organs. " + 
                    "In most cases, the flowers appear hermaphroditic in structure, but function " + 
                    "as either male or female",Image = Resource.Drawable.fruit_strawberry },
                new Product() { Category="Fruits", Name = "Watermelon",Description = "A watermelon " + 
                    "is a type of edible fruit. They are 92% water. About six percent of " + 
                    "a watermelon is sugar. This makes them very sweet. There are many " + 
                    "different tlypes of watermelon.",Image = Resource.Drawable.fruit_watermelon }}
                );                    
            }
        }
    }</product>
  9. Rebuild Solutions and run.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

R S Dodiya
Software Developer (Senior)
India India

Comments and Discussions

 
Questioncustomise every information by clicking a button PinmemberArahanayan11-Mar-13 19:39 
How can i change data list by clicking a button?
QuestionNullReferenceException Pinmembernewack28-Nov-12 17:42 
AnswerRe: NullReferenceException PinmemberR S Dodiya30-Nov-12 1:55 
AnswerRe: NullReferenceException PinmemberDrJaymz21-Jan-13 6:28 
QuestionMultiple Checkbox PinmemberSankaranarayanan.PK26-Aug-12 21:52 
GeneralMy vote of 3 PinmemberDean Oliver15-Aug-12 19:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 3 Aug 2012
Article Copyright 2012 by R S Dodiya
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid