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
Video Link
Step By Step we move forward
- Create Android application by selecting New ->Solutions and provide its name “
CustomListBox
”
Figure 1: Creating Android Project!
- Once Project is created, Open Resource Folder->Layout and Add new file of type custListItem.axml
Figure 2: Selecting New File!
Figure 3
- Add Following code in layout file
="1.0"="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
- 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)
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
.
- Now, Implement
BaseAdapter<PersInfo>
, the bare skeleton class look like to be :-
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
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.
- 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 :-
="1.0"="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>
- In Resources -> Drawable folder add few images, like I have added images of Badminton racquet, Football and SnowMan.
| | |
Snow-Man |
Football |
Badminton |
- Now add private variable
_perInfoList
of type List<PersInfo> and provide some initial values to it like this :-
_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.
- 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.
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.
- Now add
ListView.ItemClick
handler and in handler code add Toast to generate message of clicked user
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
- Now Build and Run! (this is 3.4 inch emulator image)
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