Click here to Skip to main content
Click here to Skip to main content

MonoAndroid: Writing custom generic BaseAdapter in C#

, 21 Nov 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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

Video Link



Step By Step we move forward

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

    Figure 1: Creating Android Project!

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

    Figure 2: Selecting New File! 

    Figure 3

  4. Add Following code in layout file
    <?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) 
    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 :-  
        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> as argument, and assign these values to private member listed in first step.
    • Coding 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
    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 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
    Snow-Man Football Badminton

  9. Now add private variable _perInfoList of type List<PersInfo> and provide some initial values to it like this :- 
    _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.
    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
    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)

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)

Share

About the Author

ThatsAlok
Software Developer (Senior)
India India
He used to have biography here Smile | :) , but now he will hire someone (for free offcourse Big Grin | :-D ), Who writes his biography on his behalf Smile | :)
 
He is Great Fan of Mr. Johan Rosengren (his idol),Lim Bio Liong, Nishant S and DavidCrow and Believes that, he will EXCEL in his life by following there steps!!!
 

For good 8 years he was Visual CPP MSMVP!

Comments and Discussions

 
GeneralGood Pinmemberuser998763511-Aug-13 4:35 
Questionwhy c#? PinmemberArash M. Dehghani30-Jul-13 3:17 
AnswerRe: why c#? PinmemberThatsAlok30-Jul-13 4:58 
GeneralRe: why c#? PinmemberArash M. Dehghani30-Jul-13 5:17 
Hmm, seems you have a very tight connection with MS.
1.I'm completely disagree with your opinion about VS and Eclipse, Eclipse is really perfect and good IDE, especially when you would save the money too! while VS is a MS product, so every time I see or hear M$, I know there are some caps need to be destroyed.
 
2.I really cannot count on Mono, because it's funny at first "Writing si-sharp for android!?", so certainly it converts the code in order to understandable to device/os, so what is the big differences between coding in Java and C#?! maybe delegates, properties, ..., so I thin a true android developer works with his best friend Eclipse, and I hope you will too.
 
3.I'm wondering how do you find C# closer to VC++ than Java?! Java and C are good friends, and I'm happy about recent C/C++ ISO, at least MS is not free to define and declare fully dependent architecture/platform for win machinez, all I know there are to MUCH application has written in Java for phones, and most of the suggestions are talking about Java, maybe you need to switch from MS to Oracle and Google, you know MS is alive with its windows and supporters, and sooner or later it will kicked.
 
good luck out there buddy Smile | :)
GeneralRe: why c#? PinmvpFlorian Rappl30-Jul-13 5:56 
GeneralRe: why c#? PinmemberArash M. Dehghani30-Jul-13 6:45 
AnswerRe: why c#? PinmemberThatsAlok30-Jul-13 7:31 
AnswerRe: why c#? PinmemberThatsAlok30-Jul-13 7:16 
GeneralRe: why c#? [modified] PinmemberGauravKP30-Jul-13 8:11 
GeneralRe: why c#? PinmemberArash M. Dehghani30-Jul-13 10:19 
GeneralRe: why c#? PinprotectorPete O'Hanlon5-Aug-13 0:51 
GeneralRe: why c#? PinmemberArash M. Dehghani5-Aug-13 1:16 
GeneralRe: why c#? PinprotectorPete O'Hanlon5-Aug-13 1:27 
GeneralRe: why c#? PinmemberArash M. Dehghani5-Aug-13 1:47 
GeneralRe: why c#? PinprotectorPete O'Hanlon5-Aug-13 2:09 
GeneralRe: why c#? PinmemberArash M. Dehghani5-Aug-13 2:29 
GeneralPlease don't debate about C# or Java Pinmemberquiit15-Aug-13 1:41 
AnswerRe: Please don't debate about C# or Java PinmemberThatsAlok15-Aug-13 21:47 
AnswerRe: why c#? Pinmemberfiloe22-Aug-13 5: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 | Terms of Use | Mobile
Web03 | 2.8.141220.1 | Last Updated 22 Nov 2013
Article Copyright 2013 by ThatsAlok
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid