listview也许是用的非常频繁的一个控件之一,下面我写一个xamarin的listview栗子,大家尝一尝xamarin android开发的乐趣。原谅我的大小写吧.
先来看一下最终实现的效果图:
News.cs 和NewAdapter.cs
namespace DrawerLayout.Adapter
{
public class News {
public int Pv { get; set; }
public string Title { get; set; }
public News(string title,int Pv)
{
this.Title = title;
this.Pv = Pv;
}
}
public class NewsAdapter : BaseAdapter
{
private List data;
private Context context;
public override int Count
{
get
{
return data.Count;
}
}
public NewsAdapter(List data,Context context)
{
this.data = data;
this.context = context;
}
public override Java.Lang.Object GetItem(int position)
{
return null;
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
convertView = LayoutInflater.From(context).Inflate(Resource.Layout.lv_test,parent,false);
TextView title = convertView.FindViewById(Resource.Id.tv_title);
TextView pv = convertView.FindViewById(Resource.Id.tv_pv);
pv.Text = data[position].Pv.ToString();
title.Text = data[position].Title;
return convertView;
}
}
}
listview布局lv_test.axml
最后是MainActivity.cs
namespace DrawerLayout
{
[Activity(Label = "ListViewDemo", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
int count = 1;
private List data;
private Context context;
private NewsAdapter adapter;
private ListView lv_test;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
data = new List() {
new News ("加内特的历史地位能在NBA排第几,超越德国战车?",1200),
new News ("盘点新赛季最期待的十场比赛,无湖人比赛?",560),
new News ("库里新赛季铁定无缘常规赛MVP",158200),
new News ("我服,库里,杜兰特,汤普森谁才是出手的最佳选择",900),
new News ("易建联的出场时间你能猜出来吗,大概多少",960),
new News ("卡戴珊三姐妹睡多少男人",960),
new News("科比退役后湖人到底失去多少中国的粉丝",4986),
new News("科比退役湖人签中国篮球当家背后隐藏了多少阴谋",65987)
};
adapter = new NewsAdapter(data,this);
lv_test = FindViewById(Resource.Id.lv_test);
//View lv_header = LayoutInflater.Inflate(Resource.Layout.lv_header, null);
//lv_test.AddHeaderView(lv_header);
lv_test.Adapter = adapter;
lv_test.ItemClick += (s, e) =>
{
OnClick(e.Position);
};
}
public void OnClick(int position)
{
position--;
Toast.MakeText(this,$"这条新闻有"+data[position].Pv+"次浏览量",ToastLength.Short).Show();
}
}
}
listview可以自己设置表头表位,以及分割线,下面看一看具体的方法:
这里我参考的csdn-pig写的android博客,设置listview 表头表尾丙没有这种属性,只用以下几个方法
listview demo 下载链接 : ListView例子源码下载