標籤:
前言
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 listview綁定資料及點擊事件