標籤:
導讀
1.視圖及資料庫的建立
2.listview資料繫結
3.listview的點擊事件
本文
如何建立一個listview,大家可以看這裡,基本流程操作是一模一樣的,我就不多說了,然後就是建立一個資料庫,代碼如下
class Sqlite : SQLiteOpenHelper { public Sqlite(Context context) : base(context, "notebooksql.db", null, 1) { } public override void OnCreate(SQLiteDatabase db) { db.ExecSQL("CREATE TABLE NoteBooksql ( _id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,title TEXT NOT NULL,context TEXT NOT NULL,time TIME NOT NULL)"); db.ExecSQL("INSERT INTO NoteBooksql (title,context,time)values(‘這是第一篇筆記‘,‘筆記筆記第一篇筆記筆記筆記第一篇筆記筆記筆記第一篇筆記筆記筆記第一篇筆記‘,‘2015-3-15‘)"); db.ExecSQL("INSERT INTO NoteBooksql (title,context,time)values(‘這是第二篇筆記‘,‘筆記筆記第二篇筆記筆記筆記第二篇筆記筆記筆記第二篇筆記筆記筆記第二篇筆記‘,‘2015-3-15‘)"); } public override void OnUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.ExecSQL("DROP TABLE IF EXISTS NoteBooksql"); OnCreate(db); } }
這裡設定了一個自增主鍵和三個欄位,然後我添加了兩條預設資料。
資料庫建立完成之後我們開啟Activity1,繼承listactivity,給listview進行綁定資料
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); vdb = new Sqlite(this); cursor = vdb.ReadableDatabase.RawQuery("SELECT * FROM NoteBooksql", null); StartManagingCursor(cursor); string[] title = new string[] { "title", "time" }; int[] time = new int[] { Resource.Id.textView1, Resource.Id.textView2 }; ListAdapter = new SimpleCursorAdapter(this, Resource.Layout.Item, cursor, title, time); }
如上
有了資料的listview卻不能操作那邊是毫無作用,我們可以重新OnListItemClick方法給listview添加點擊事件
protected override void OnListItemClick(ListView l, View v, int position, long id) { string title= v.FindViewById<TextView>(Resource.Id.textView1).Text.ToString(); string time = v.FindViewById<TextView>(Resource.Id.textView2).Text.ToString(); vdb = new Sqlite(this); cursor = vdb.ReadableDatabase.RawQuery("SELECT * FROM NoteBooksql where title= ‘" + title+ "‘ and time = ‘" + time + "‘", null); cursor.MoveToFirst(); string Nid = cursor.GetString(cursor.GetColumnIndex("_id")); var intent = new Intent(this, typeof(Note)); intent.PutExtra("id", Nid); StartActivity(intent); this.Finish(); }
這裡為了圖方便,我直接根據title和time擷取id。
如下
Xamarin.Android 記事本(一)