MonoAndroid: Using GridView in your mobile application
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
and i
ew 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
`- Create Android application by selecting New ->Solutions and provide its name “
CustomGridView
”
Figure 1: Creating Android Project!
-
Once Project is created, Open Resource Folder->Layout and Add new file of type
custGridViewItem.axml
Figure 2: Selecting New File!Figure 3: Select Layout file
- 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"> <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
AndTextView
See how it look like in XamarinTm Studio Designer, once created :-Figure 4: Designer view of GridView custom item
- First add
- Now add class by name
myGVItemAdapter
and inherit from abstract generic classBaseAdpater<FlimStarInfo>,
here is code forFlimStarInfo
class. (Similar to Step2, instead of adding Layout file, add C# class file)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 asGridViewItem
forGridView
. - Now, Implement
BaseAdapter<FlimStarInfo>
, the bare skeleton class look like to be :-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>
andActivity
- Add parameterized constructor, which take
Activity
andList<FlimStarInfo>
as argument, and assign these values to private member listed in first step. - Coding GetItemId,
Count
andthis [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 = _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, usingFindViewById
method find TextView and ImageView and assign them values fromFlimStarInfo
item based on incoming position. - Now Add two private member of type
- 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 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.
- In Resources -> Drawable folder add few images, like I have added images of few famous Flim artist from India.
Madhuri Dixit Aishwarya Rai Bachan Akshay Kumar Arjun Rampal Abhay Deol Chiranjeevi Shahrukh Khan Preity Zinta R Madhavan Kajol Devgan Meena Kumari Juhi Chawla -
Now add private method
getFlimStarInformation
of type List<FlimStarInfo> and provide some initial values to it like this :-
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 ourCustomAdapter
which I going to explain in next step.
- 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.
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. - Now add
GridView.ItemClick
handler and in handler code add Toast to generate message of clicked usergvObject.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
You can read more aboutAdapterView.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.Toast
class here - Now Build and Run!
Android 3.4 Inch Android 4 inch. - For running this screenshot I have changed
GridView
propertiesandroid:numColumns to
"auto_fit" andandroid:columnWidth
to "150dp" in Main.Axml
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!
- MonoAndroid: Writing custom generic BaseAdapter in C#
- MonoAndroid: Using TabHost in your mobile applications
- MonoAndroid: Using Fragments in mobile app
- MonoAndroid: Using dotnet webservice (ASMX)
- MonoAndroid: Using Started Service
- MonoAndroid: Calling secondary activity
- MonoAndroid: Writing ExpandableListView amd BaseExpandableListAdapter in C#
- MonoAndroid: Using AlertDialog
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