Click here to Skip to main content
15,867,594 members
Articles / Programming Languages / C#
Tip/Trick

A Little Better BaseAdapter<T>

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
19 Apr 2014CPOL2 min read 12.2K   6   4
BaseAdapter that removes the need for some tedious coding

Introduction

Xamarin.Android is very, very good. I'm just in love with it. But as it uses GUI from Android platform itself displaying items in ListView (ListBox) or Spinner (ComboBox) can be really boring as you have to write adapters & GUI again and again. Even if all you want is to display list of strings, you have to code it. No shortcut like:

C#
myListBox.ItemsSource=myStringList;

Update

Initially, I omitted this part as I thought the code was self explanatory, forgetting that this is a beginner article. As Dave Kreskowiak pointed, without some explanation this was just a code dump.

Let's say we need to display a list of strings in dialog box. To accomplish this, some steps are needed:

  1. XML template for single item of the list (jenerik_buyuk.axml)
  2. Adapter to hold and display our data (adapter_baz.cs)
  3. XML template for dialog box (dlg_jenerik.axml)
  4. Custom dialog implementation to display data (dlg_jenerik.cs)
  5. Finally, display our list of strings (last code block)

So I decided to share some code that I usually use. :) (no pun intended)

  1. The jenerik_buyuk.axml

    XML
    <?xml version="1.0" encoding="UTF-8"?>
    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_height="wrap_content" android:layout_width="wrap_content" 
        android:padding="5dp">
      <TextView android:id="@+id/txtJenerik_buyuk" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:gravity="center_vertical|center_horizontal" 
        android:focusable="false" android:textsize="24sp">
    </LinearLayout>  
  2. adapter_baz.cs

    C#
    public class adapter_baz<T>:BaseAdapter<t>
        {
            internal List<t> _internalList = null;
            internal LayoutInflater myInflater = null;
    
            public int id_txtJenerik { get { return Resource.Id.txtJenerik_buyuk; } }
            public int id_vwJenerik { get { return Resource.Layout.jenerik_buyuk; } }
    
            public Func<layoutinflater,> func_onViewRequested { get; set; }
    
            #region ctor
    
            public adapter_baz(Context cxt, List<t> inputList)
            {
                myInflater = LayoutInflater.FromContext(cxt);
                _internalList = inputList;
            }
    
            public adapter_baz(Context cxt)
            {
                myInflater = LayoutInflater.FromContext(cxt);
                _internalList = null;
            }
    
            #endregion
    
            public override T this[int position] { get { return this._internalList[position]; } }
            public override int Count { get { return this._internalList.Count; } }
            public override Java.Lang.Object GetItem(int position) { return position; }
            public override long GetItemId(int position) { return position; }
    
            public override View GetView(int position, View convertView, ViewGroup parent)
            {
                var bu = this[position];
                if (func_onViewRequested != null)
                    return func_onViewRequested(myInflater, convertView, parent, bu);
    
                var yen = get_GenericView(convertView);
                set_GenericViewContent(yen, bu.ToString(), position);
                return yen;
            }
    
            View get_GenericView(View convertView)
            {
                if (convertView != null)
                    return convertView;
                return myInflater.Inflate(id_vwJenerik, null);
            }
    
            void set_GenericViewContent(View vw, string text, int pozisyon = -1)
            {
                TextView txt = vw.FindViewById<textview>(id_txtJenerik);
    
                txt.Text = text;
                if (pozisyon != -1)
                    txt.Tag = pozisyon;
            }        
        }
  3. dlg_jenerik.axml

    XML
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
        android:orientation="horizontal" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent">
      <ListView android:id="@+id/lv_dlg_jenerik" android:layout_width="fill_parent" 
        android:layout_height="fill_parent">
    </LinearLayout> 
  4. dlg_jenerik.cs

    C#
    public class dlg_jenerik<T> : Dialog
        {
            public adapter_baz<t> adp { get; private set; }
    
            public Action<object> OnItemClicked { get; set; }
    
            public dlg_jenerik(Context cxt, adapter_baz<t> gelenAdp)
            {
                adp = gelenAdp;
                ctor_common();
            }
            
            public dlg_jenerik(Context cxt)
            {
                ctor_common();
            }
    
            private void ctor_common()
            {
                SetContentView(Resource.Layout.dlg_jenerik);
    
                OnItemClicked = null;
    
                var lv = (ListView)FindViewById(Resource.Id.lv_dlg_jenerik);
                lv.Adapter = adp;
                lv.ItemsCanFocus = false;
                lv.ItemClick += new EventHandler<adapterview.itemclickeventargs>(lv_ItemClick);
            }
    
            void lv_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
            {
                var bu = adp[e.Position];
                Dismiss(); 
                if(OnItemClicked !=null)
                    OnItemClicked(bu);
            }
        }</adapterview.itemclickeventargs> 

Using the Code

Sorry for the long introduction. Now when all is ready, the usage is simple:

C#
var list = new List<string>(){"bir","iki","uc","dort"};
var dlg = new dlg_jenerik(this,list);
dlg.OnItemClicked=(param)=>
{ HelperUI.ShowToast(param.ToString());};
dlg.Show(); 

Points of Interest

  1. You can change how each item is shown by providing your own func_onViewRequested in adapter_baz
  2. You can provide your own event handler to change what to do when item gets clicked by providing Action<object> in dlg_jenerik
  3. Logic for LongItemClick is the same. I was just lazy to implement it. :)

Hope these snippets help someone as some tutorial like this would have been VERY useful for me some 7-8 months ago.

What Can Be Improved?

You may decide that trivial List<T> in adapter_baz<T> _internalList is too trivial for you, and you need paging or data virtualization. In this case, you can use VirtualizingCollection<T>. An excellent work by Paul McClean.

http://www.codeproject.com/Articles/34405/WPF-Data-Virtualization

This is a very neat and useful piece of code.

License

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


Written By
Software Developer
Turkmenistan Turkmenistan
I'm a freelancer. C#,WPF,CouchDB,Sqlite,Xamarin.Forms,Xamarin.Android

Comments and Discussions

 
QuestionNot quite Pin
Dave Kreskowiak20-Apr-14 3:10
mveDave Kreskowiak20-Apr-14 3:10 
AnswerRe: Not quite Pin
Begench Amanov20-Apr-14 3:43
Begench Amanov20-Apr-14 3:43 
Explanation for what?
1) create template for single item of the list
2) create generic adapter
3) create template for listview
4) create generic dialog to display listview
5) display list of strings in dialog
Seems fairly obvious to me
B.Amanow/Turkmenistan

GeneralRe: Not quite Pin
Dave Kreskowiak20-Apr-14 4:04
mveDave Kreskowiak20-Apr-14 4:04 
GeneralRe: Not quite Pin
Begench Amanov20-Apr-14 4:15
Begench Amanov20-Apr-14 4:15 

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.