xamarin.android listview绑定数据及点击事件
前言
listview是用来显示数据列表的一个控件,今天给大家带来如何使用cursor进行数据绑定以及点击事件。
导读
1.如何创建一个listview
2.如何使用cursor进行绑定数据
3.listview的点击事件
正文
1.如何创建一个listview
这里我们自定义一个listview的视图,首先打开Main.axml,拖一个listview放进去。
右击Layout新建一个视图,名为UserListItemLayout.axml,拖两个textview进去,如图
这样我们就完成了一个自定义的listview,
是用listview需要继承listactivity类,也可以不继承,不继承也有不继承的方法,我会把两个方法都写出来。
SQLite vdb; ICursor cursor; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); //SetContentView(Resource.Layout.Main); ActionBar.SetDisplayHomeAsUpEnabled(true); vdb = new SQLite(this); cursor = vdb.ReadableDatabase.RawQuery("SELECT * FROM TestTable", null); StartManagingCursor(cursor); string[] name = new string[]{ "name", "phone" }; int[] phone = new int[] { Resource.Id.textName, Resource.Id.textPhone }; ListAdapter = new SimpleCursorAdapter(this, Resource.Layout.UserListItemLayout, cursor, name,phone); }
这里我们给cursor绑定了数据,如何创建数据库请参考YZF的Xamarin.Android之SQLiteOpenHelper,这里继承了listactivity,所以无法使用setcontentview。
如何需要使用setcontentview的话,我们可以不继承listactivity,只需要把代码改成这样既可
public class Activity1 : Activity { SQLite vdb; ICursor cursor; ListView listView; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); //SetContentView(Resource.Layout.Main); ActionBar.SetDisplayHomeAsUpEnabled(true); listView = FindViewById<ListView>(Resource.Id.listView1); vdb = new SQLite(this); cursor = vdb.ReadableDatabase.RawQuery("SELECT * FROM TestTable", null); StartManagingCursor(cursor); string[] name = new string[]{ "name", "phone" }; int[] phone = new int[] { Resource.Id.textName, Resource.Id.textPhone }; listview.Adapter = new SimpleCursorAdapter(this, Resource.Layout.UserListItemLayout, cursor, name,phone); }
效果图如下
3.listview的点击事件
这里listview的点击事件有两种方法,第一种是继承listactivity使用的方法,第二种是不继承listactivity的使用方法。
这里我们可以直接重写OnListItemClick方法既可调用listview的点击事件
protected override void OnListItemClick(ListView l, View v, int position, long id) { }
或者你使用了第二种方法
this.listView.ItemClick += new EventHandler<AdapterView.ItemClickEventArgs>(ListView_ItemClick); void ListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e) { }
最后效果图如下
分类:
xamarin android
标签:
xamarin.android
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· What?废柴, 还在本地部署DeepSeek吗?Are you kidding?
· 程序员转型AI:行业分析
· 深入集成:使用 DeepSeek SDK for .NET 实现自然语言处理功能
· 为DeepSeek添加本地知识库
· .NET程序员AI开发基座:Microsoft.Extensions.AI