Click here to Skip to main content
15,860,859 members
Articles / Mobile Apps / Xamarin

MonoAndroid: Writing custom generic BaseAdapter in C#

Rate me:
Please Sign up or sign in to vote.
4.65/5 (11 votes)
21 Nov 2013CPOL4 min read 57.2K   592   27   19
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)


Written By
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!!!

He started with Visual C++ then moved to C# then he become language agnostic, you give him task,tell him the language or platform, he we start immediately, if he knows the language otherwise he quickly learn it and start contributing productively

Last but not the least, For good 8 years he was Visual CPP MSMVP!

Comments and Discussions

 
GeneralGood Pin
David H. Wright11-Aug-13 3:35
professionalDavid H. Wright11-Aug-13 3:35 
QuestionMessage Closed Pin
30-Jul-13 2:17
user558320830-Jul-13 2:17 
AnswerRe: why c#? Pin
ThatsAlok30-Jul-13 3:58
ThatsAlok30-Jul-13 3:58 
GeneralMessage Closed Pin
30-Jul-13 4:17
user558320830-Jul-13 4:17 
GeneralRe: why c#? Pin
Florian Rappl30-Jul-13 4:56
professionalFlorian Rappl30-Jul-13 4:56 
GeneralMessage Closed Pin
30-Jul-13 5:45
user558320830-Jul-13 5:45 
AnswerRe: why c#? Pin
ThatsAlok30-Jul-13 6:31
ThatsAlok30-Jul-13 6:31 
AnswerRe: why c#? Pin
ThatsAlok30-Jul-13 6:16
ThatsAlok30-Jul-13 6:16 
GeneralRe: why c#? Pin
GauravKP30-Jul-13 7:11
professionalGauravKP30-Jul-13 7:11 
GeneralMessage Closed Pin
30-Jul-13 9:19
user558320830-Jul-13 9:19 
GeneralRe: why c#? Pin
Pete O'Hanlon4-Aug-13 23:51
subeditorPete O'Hanlon4-Aug-13 23:51 
GeneralMessage Closed Pin
5-Aug-13 0:16
user55832085-Aug-13 0:16 
GeneralRe: why c#? Pin
Pete O'Hanlon5-Aug-13 0:27
subeditorPete O'Hanlon5-Aug-13 0:27 
GeneralMessage Closed Pin
5-Aug-13 0:47
user55832085-Aug-13 0:47 
GeneralRe: why c#? Pin
Pete O'Hanlon5-Aug-13 1:09
subeditorPete O'Hanlon5-Aug-13 1:09 
GeneralMessage Closed Pin
5-Aug-13 1:29
user55832085-Aug-13 1:29 
GeneralPlease don't debate about C# or Java Pin
Quí Nguyễn NT15-Aug-13 0:41
Quí Nguyễn NT15-Aug-13 0:41 
AnswerRe: Please don't debate about C# or Java Pin
ThatsAlok15-Aug-13 20:47
ThatsAlok15-Aug-13 20:47 
AnswerRe: why c#? Pin
Florian Rosmann22-Aug-13 4:46
Florian Rosmann22-Aug-13 4:46 

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

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