public
Last active

How to do custom layouts in Android with ListView

  • Download Gist
layout.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
using System;
 
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Collections.Generic;
using System.Linq;
 
namespace CustomLayoutTest
{
[Activity (Label = "CustomLayoutTest", MainLauncher = true)]
public class Activity1 : Activity
{
int count = 1;
 
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
 
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
 
var items = new[] {
new NameWithCount { Name = "Hats", Count = 32 },
new NameWithCount { Name = "Economics Textbooks", Count = 17 },
new NameWithCount { Name = "Robots", Count = 110 },
};
 
var lv = FindViewById<ListView> (Resource.Id.listView1);
lv.Adapter = new MyCoolAdapter (items.ToList (), this);
}
}
 
public class MyCoolAdapter : BaseAdapter<NameWithCount>
{
Activity _parent;
List<NameWithCount> _items;
 
public MyCoolAdapter(List<NameWithCount> items, Activity parent)
{
_parent = parent;
_items = items;
}
 
public override View GetView (int position, View convertView, ViewGroup parent)
{
var view = _parent.LayoutInflater.Inflate (Resource.Layout.NameWithCountView, null);
 
var name = view.FindViewById<TextView> (Resource.Id.textView1);
var count = view.FindViewById<TextView> (Resource.Id.textView2);
 
name.Text = _items [position].Name;
count.Text = _items [position].Count.ToString();
return view;
}
 
public override int Count {
get {
return _items.Count;
}
}
 
public override NameWithCount this [int position] {
get {
return _items[position];
}
}
 
public override long GetItemId(int position)
{
return position;
}
}
 
 
public class NameWithCount
{
public string Name { get; set; }
public int Count { get; set; }
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.