Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Xamarin

MonoAndroid: Writing custom generic BaseAdapter in C#

4.65/5 (11 votes)
21 Nov 2013CPOL4 min read 59.9K   592  
Using generic BaseAdapter to generate ListView

Introduction

From last few weeks I am working on Mono-Android and In this article I am going to create custom generic BaseAdapter derived class to generate list view!

Now for start, creating ListView is not as straight forward as of ASP.net ListView/GridView, where we can attach the list collection directly to ListView and see the result. Here in android world, things is little different, every item in list view represent a view and you have to provide values to control present in that view. During my learning, I feel like I am sub classing CButton class in MFC Image 1

Video Link

Image 2

Step By Step we move forward

  1. Create Android application by selecting New ->Solutions and provide its name “CustomListBox

    Image 3

    Figure 1: Creating Android Project!

  2.  
  3. Once Project is created, Open Resource Folder->Layout and Add new file of type custListItem.axml

    Image 4

    Figure 2: Selecting New File! 

    Image 5

    Figure 3

  4. Add Following code in layout file
    XML
    <?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"
        android:minWidth="25px"
        android:minHeight="25px">
        <LinearLayout
            android:orientation="horizontal"
            android:minWidth="25px"
            android:minHeight="25px"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/linearLayout1">
            <ImageView
                android:src="@android:drawable/ic_menu_gallery"
                android:layout_width="46.7dp"
                android:layout_height="wrap_content"
                android:id="@+id/IMG1"
                android:layout_marginRight="9.3dp" />
            <TextView
                android:text="Text"
                android:layout_width="159.3dp"
                android:layout_height="fill_parent"
                android:id="@+id/textName"
                android:layout_marginRight="30.6dp"
                android:gravity="center_vertical"
                android:paddingRight="10dp"
                android:paddingLeft="10dp" />
            <TextView
                android:text="Text"
                android:layout_width="match_parent"
                android:layout_height="fill_parent"
                android:id="@+id/textAge"
                android:gravity="center_vertical"
                android:paddingLeft="10dp" />
        </LinearLayout>
    </LinearLayout> 
    Let me explain how exactly I created this layout file (you can understand it as UI front)
    • Now add LinearLayout with orientation “Horizontal”
    • In this Horizontal Linear Layout add ImageView and two TextView
    • Rest I have done little tweaking for formatting ImageView And TextView
  5. Now add class by name customListAdapter and inherit from abstract generic class BaseAdpater<PersInfo>, here is code for PersInfo class. (Similar to Step2, instead of adding Layout file, add C# class file) 
    C#
    public class PersInfo
        {
            public string Name {get;set;}
            public string Age  {get;set;}
            public int ImageID {get;set;}
        } 
    Each object of above class will act as ListItem for ListView.

  6. Now, Implement BaseAdapter<PersInfo>, the bare skeleton class look like to be :-  
    C#
    public class customListAdapter1: BaseAdapter<PersInfo>
    {
        #region implemented abstract members of BaseAdapter
        public override long GetItemId (int position)
        {
            throw new NotImplementedException ();
        }
        public override View GetView (int position, View convertView, ViewGroup parent)
        {
            throw new NotImplementedException ();
        }
        public override int Count {
            get {
                throw new NotImplementedException ();
            }
        }
        #endregion
        #region implemented abstract members of BaseAdapter
        public override PersInfo this [int position] {
            get {
                throw new NotImplementedException ();
            }
        }
        #endregion
    }
    
    • Now Add two private member of type List<PersInfo> and Activity
    • Add parameterized constructor, which take Activity and List<PersInfo><persinfo> as argument, and assign these values to private member listed in first step.
    • Coding <code><code><code>GetItemId, Count and this [int position] is fairly simple as in GetItemId: we are just returning the position as itemID, In Count: we returning list count and this [int position]: we will return item in specified position.  
    • Now we are on most typical part, writing GetView function
    C#
    public override View GetView (int position, View convertView, ViewGroup parent)
    {
       var item = this._perInfoList [position];
       var view = convertView;
       
       if (convertView == null || !(convertView is LinearLayout))
        view = _Context.LayoutInflater.Inflate (Resource.Layout.custListItem, parent, false);
    
        var textName = view.FindViewById (Resource.Id.textName) as TextView;
        var textage = view.FindViewById (Resource.Id.textAge) as TextView;
        var textplace = view.FindViewById (Resource.Id.IMG1) as ImageView;
        textName.SetText (item.Name, TextView.BufferType.Normal);
        textage.SetText (item.Age, TextView.BufferType.Normal);
        textplace.SetImageResource(item.ImageID);
        return view;
    }

    Here we pick up the item, based on position then we will check convertView has memory. If not then we use saved Activity object to create view of type custListItem layout.

    Now as we already provided custListItem view, using FindViewById method find TextView and ImageView and assign them values from PersInfo item based on incoming position.

  7. Now your adapter and ListItem view is ready, now we will program main activity to use above code. Add a ListView Control in Main.axml, after that your code would look some like this :- 
    XML
    <?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"
        android:minWidth="25px"
        android:minHeight="25px">
        <ListView
            android:minWidth="25px"
            android:minHeight="25px"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/listView1" />
    </LinearLayout> 

  8. In Resources -> Drawable folder add few images, like I have added images of Badminton racquet, Football and SnowMan
    Image 6Image 7Image 8
    Snow-Man Football Badminton

  9. Now add private variable _perInfoList of type List<PersInfo> and provide some initial values to it like this :- 
    C#
    _perInfoList = new System.Collections.Generic.List<PersInfo>()
    {
        new PersInfo(){ Name="Alok Gupta",Age="31",ImageID= Resource.Drawable.SnowMan},
        new PersInfo(){ Name="Jasdeep Singh",Age="31",ImageID= Resource.Drawable.FootBall},
        new PersInfo(){ Name="Ritesh Thakur",Age="34",ImageID= Resource.Drawable.Badmitton}
    };
    Here, this list is act as feeder for our CustomAdapter which I going to explain in next step.

  10. Now you have find ListView using FindViewById<ListView> using id “Resource.Id.listView1” and create our customListAdapter by passing current activity and list collection we created in last step and assign it to ListView Object adapter property.
    C#
    var listViewObj = FindViewById<ListView> (Resource.Id.listView1);
    listViewObj.Adapter = new customListAdapter (this, _perInfoList);
    ListView will internally call customListAdapter GetView and Count Method to built list view.

  11. Now add ListView.ItemClick handler and in handler code add Toast to generate message of clicked user
    C#
    listViewObj.ItemClick += new EventHandler<AdapterView.ItemClickEventArgs> (OnListItemClick);
    
    void OnListItemClick (object sender, AdapterView.ItemClickEventArgs e) {
    Toast.MakeText (this, "You Click on name " + _perInfoList [e.Position].Name, ToastLength.Long).Show ();
    } 
    You can read more about Toast class here

  12. Now Build and Run! (this is 3.4 inch emulator image)

    Image 9

Points of Interest

I have used MonoAndroid for C# and Xamarin Studio to build this tutorial.  Watch out, if I continue learning it, you can expect more articles coming soon. 

Though Xamarin Studio is proprietary software, however they provide free starter version to built, test and publish android application. I am using same for my learning. 

Articles in this series!

Tips/Tricks in this Series

History  

  • 30-Jul-2013: First Version
  • 01-Aug-2013: Forget something initially, now Included. 
  • 22-Aug-2013: Updated Other article in this series listing
  • 06-Sept-2103: Updated tips and tricks section. 
  • 11-Oct-2103: Updated article section. 
  • 05-Nov-2013: Added Video link
  • 22-Nov-2013: Updated other article section

License

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