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

MonoAndroid: Using GridView in your mobile application

4.78/5 (22 votes)
21 Nov 2013CPOL5 min read 78.6K   2K  
Demonstration of Android::GridView

Introduction

As mentioned in my previous article about generic BaseAdapter "for last few weeks I am working on Mono-Android" and now in this article we will see demonstration of Android GridView control.

Now for start, creating as GridView is not as straight forward as of ASP.net ListView/GridView, where we can attach the list collection directly to GridView and see the grid full of data. 

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. However main difference between ListV<code>iew and GridView is that you can define multiple items in rows in GridView (Thats how Grid's works). That is missing in ListView (though we can design ListView item view to achieve that, however little complicated). 

Grid Control is generally used in creating galleries and other stuffs! 

So we can safely assume ListView more closer to List Control and GridView More closer to Grid control of .Net world.In this article we will create Indian Film stars grid view.  

Step By Step we move forward

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


    Image 1Figure 1: Creating Android Project!

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

    Image 2


    Figure 2: Selecting New File!  

    Image 3

    Figure 3: Select Layout file 

  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">
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/linearLayoutHorizontal">
            <ImageView
                android:src="@android:drawable/ic_menu_gallery"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:id="@+id/imgPers"
                android:layout_gravity="center_vertical"
                android:paddingRight="2pt"
                android:layout_marginBottom="4.7dp" />
            <LinearLayout
                android:orientation="vertical"
                android:minWidth="25px"
                android:minHeight="25px"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/linearLayout1">
                <TextView
                    android:text="Text"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/txtName"
                    android:paddingLeft="3pt" />
                <TextView
                    android:text="Text"
                    android:layout_width="match_parent"
                    android:layout_height="fill_parent"
                    android:id="@+id/txtAge"
                    android:typeface="normal"
                    android:textSize="5pt"
                    android:paddingLeft="3pt"
                    android:layout_marginLeft="4.0dp" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
        Let me explain how exactly I created this layout file
    • First add LinearLayout with “Horizontal” orientation
    • In this Horizontal Linear Layout add ImageView
    • Now Add another LinearLayout with Vertical orientation
    • In this newly added linear layout add two TextView
    • Rest I have done little tweaking  for formatting  ImageView And TextView

    See how it look like in XamarinTm Studio Designer, once created :-

    Image 4

    Figure 4: Designer view of GridView custom item

     
  5. Now add class by name myGVItemAdapter and inherit from abstract generic class BaseAdpater<FlimStarInfo>,  here is code for FlimStarInfo class. (Similar to Step2, instead of adding Layout file, add C# class file) 
    C#
    public class FlimStarInfo
        {
            public string Name {get;set;}
            public string Age  {get;set;}
            public int ImageID {get;set;}
        } 
    Each object of above class will act as GridViewItem for GridView.


  6. Now, Implement BaseAdapter<FlimStarInfo>, the bare skeleton class look like to be :-  
    C#
        public class myGVItemAdapter: 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<FlimStarInfo> and Activity
    • Add parameterized constructor, which take Activity and List<FlimStarInfo> 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 
    C#
    public override View GetView (int position, View convertView, ViewGroup parent)
    {
    
     var item = _lstFlimStarInfo [position];
      if(convertView == null)
     convertView = _CurrentContext.LayoutInflater.Inflate(Resource.Layout.custGridViewItem,null);
    
     convertView.FindViewById<textview> (Resource.Id.txtName).Text = item.Name;
     convertView.FindViewById<textview> (Resource.Id.txtAge).Text = item.Age.ToString();
     convertView.FindViewById<imageview>(Resource.Id.imgPers).SetImageResource (item.ImageID);
    
     return convertView;
    }

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

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

  7. Now your adapter and GridViewAdapter is ready, now we will program main activity to use above code. Add a
    GridView 
    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">
        <GridView
            android:minWidth="25px"
            android:minHeight="25px"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/gvCtrl" />
    </LinearLayout>

    Nothing extraordinary, I just drag and dropped GridView on layout and saved it.


  8. In Resources -> Drawable folder add few images, like I have added images of few famous Flim artist from India.

    Image 5 Image 6 Image 7 Image 8 Image 9 Image 10
    Madhuri Dixit Aishwarya Rai Bachan Akshay Kumar Arjun Rampal Abhay Deol Chiranjeevi
    Image 11 Image 12 Image 13 Image 14 Image 15 Image 16
    Shahrukh Khan Preity Zinta R Madhavan Kajol Devgan Meena Kumari Juhi Chawla


  9. Now add private method getFlimStarInformationof type List<FlimStarInfo> and provide some  initial values to it like this :- 
    C#
    List<flimstarinfo> getFlimStarInformation ()
    {
    
    List<flimstarinfo> listItem = new List<flimstarinfo> () {
    new FlimStarInfo(){Name ="Shahrukh", Age=47,ImageID= Resource.Drawable.shahrukh},
    new FlimStarInfo(){Name ="Preity", Age=38,ImageID= Resource.Drawable.Preity},
    new FlimStarInfo(){Name ="Chiranjeevi", Age=57,ImageID= Resource.Drawable.che},
    new FlimStarInfo(){Name ="Meena", Age=39,ImageID= Resource.Drawable.Meena},
    new FlimStarInfo(){Name ="Madhavan", Age=43,ImageID= Resource.Drawable.maddy},
    new FlimStarInfo(){Name ="Madhuri", Age=41,ImageID= Resource.Drawable.Madhuri},
    new FlimStarInfo(){Name ="Arjun", Age=40,ImageID= Resource.Drawable.arjunram},
    new FlimStarInfo(){Name ="Kajol", Age=38,ImageID= Resource.Drawable.Kajol},
    new FlimStarInfo(){Name ="Akshay", Age=45,ImageID= Resource.Drawable.akshay},
    new FlimStarInfo(){Name ="Aishwarya", Age=39,ImageID= Resource.Drawable.Aishwarya},
    new FlimStarInfo(){Name ="Abhay", Age=37,ImageID= Resource.Drawable.abhay},
    new FlimStarInfo(){Name ="Juhi", Age=45,ImageID= Resource.Drawable.Juhi}
    };
    	return listItem;
    }
    Here, this list is act as feeder for our CustomAdapter which I going to explain in next step.

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

  11. Now add GridView.ItemClick handler and in handler code add Toast to generate message of clicked user
    C#
    gvObject.ItemClick += new EventHandler<AdapterView.ItemClickEventArgs> (OnGridView_ItemClicked);
    
    void OnGridView_ItemClicked (object sender, AdapterView.ItemClickEventArgs e)
    {
     string selectedName = e.View.FindViewById<TextView> (Resource.Id.txtName).Text;
     Toast.MakeText (this, "You Click on name " + selectedName, ToastLength.Long).Show ();
    }

    Here using AdapterView.ItemClickEventArgs argument we retrieve the clicked View and using (now my favourite) FindViewById, get the clicked cell data, and then using  Toast, who it to user.

    You can read more about Toast class here

  12. Now Build and Run!
    Image 17    Image 18
    Android 3.4 Inch     Android 4 inch.
  13. For running this screenshot  I have changed GridView properties android:numColumns to "auto_fit" and android:columnWidth to "150dp" in Main.Axml


    Image 19
    Android Device 7 Inch: Landscape

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. 

Other articles in this series!

Tips/Tricks in this Series

History   

  • 01-Aug-2013: First Version
  • 22-Aug-2013: Added section "Other Article in this series"
  • 04-Sept-2013 : Update "Other Article in this Series" column  
  • 06-Sept-2013 : Added section for Tips/Trick 
  • 11-Oct-2013 : Updated article section 
  • 05-Nov-2013: Updated article section 
  • 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)