前言
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) { }
最后效果圖如下