Click here to Skip to main content
15,867,594 members
Articles / Mobile Apps / Xamarin

MonoAndroid: Using GridView in your mobile application

Rate me:
Please Sign up or sign in to vote.
4.78/5 (22 votes)
21 Nov 2013CPOL5 min read 75.9K   2K   39   15
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)


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

 
Questionopen image on click Pin
Member 1241607217-Apr-17 23:51
Member 1241607217-Apr-17 23:51 
QuestionGreat article for new bee's Pin
Member 879873428-Feb-16 5:16
Member 879873428-Feb-16 5:16 
QuestionRequest for another example... Pin
Member 111316882-Aug-15 19:54
Member 111316882-Aug-15 19:54 
QuestionThank You! Pin
esgalsiz6617-Dec-14 19:43
esgalsiz6617-Dec-14 19:43 
QuestionNewbie trying to understand more Pin
Member 112106566-Nov-14 18:22
Member 112106566-Nov-14 18:22 
AnswerRe: Newbie trying to understand more Pin
ThatsAlok7-Nov-14 0:24
ThatsAlok7-Nov-14 0:24 
Questionfor error Pin
Member 1027840827-Sep-13 3:55
Member 1027840827-Sep-13 3:55 
GeneralMy vote of 5 Pin
Prasad Khandekar6-Sep-13 5:00
professionalPrasad Khandekar6-Sep-13 5:00 
AnswerRe: My vote of 5 Pin
ThatsAlok6-Sep-13 6:22
ThatsAlok6-Sep-13 6:22 
QuestionThank you Pin
Ammar Al-hamdabni5-Sep-13 9:34
Ammar Al-hamdabni5-Sep-13 9:34 
AnswerRe: Thank you Pin
ThatsAlok5-Sep-13 20:05
ThatsAlok5-Sep-13 20:05 
GeneralMy vote of 5 Pin
Anurag Gandhi22-Aug-13 19:35
professionalAnurag Gandhi22-Aug-13 19:35 
AnswerRe: My vote of 5 Pin
ThatsAlok23-Aug-13 1:25
ThatsAlok23-Aug-13 1:25 
GeneralMy vote of 5 Pin
ketan italiya13-Aug-13 0:24
ketan italiya13-Aug-13 0:24 
AnswerRe: My vote of 5 Pin
ThatsAlok13-Aug-13 2:21
ThatsAlok13-Aug-13 2:21 

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.