本文实例为大家分享了Intent如何实现一个简单的记事本功能的演示过程,供大家参考,具体内容如下
1、运行截图
单击右上角【…】会d出【添加】菜单项,长按某条记录会d出快捷菜单【删除】项。
2、主要设计步骤
(1)添加引用
鼠标右击【引用】à【添加引用】,在d出的窗口中勾选“System.Data”和“System.Data.sqlite”,如下图所示:
注意:不需要通过NuGet添加sqlite程序包,只需要按这种方式添加即可。
(2)添加图片
到AndroID SDK API 23的Samples的NotePad例子下找到app_notes.png,将其添加到该项目中,并将其换名为ch12_app_notes.png。
(3)添加ch1205_NoteEditor.axml文件
<?xml version="1.0" enCoding="utf-8"?><vIEw xmlns:androID="http://schemas.androID.com/apk/res/androID" androID:ID="@+ID/note" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:padding="5dip" androID:scrollbars="vertical" androID:fadingEdge="vertical" androID:gravity="top" androID:textSize="22sp" androID:cAPItalize="sentences" />
(4)添加ch1205_Main.axml文件
<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" androID:layout_wIDth="fill_parent" androID:layout_height="wrap_content" androID:orIEntation="horizontal" androID:background="#ffffff" androID:padding="10px"> <ImageVIEw androID:ID="@+ID/icon" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:src="@drawable/ch12_app_notes" /> <linearLayout androID:layout_wIDth="fill_parent" androID:layout_height="wrap_content" androID:orIEntation="vertical" androID:paddingtop="6px"> <TextVIEw androID:ID="@+ID/body" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" /> <TextVIEw androID:ID="@+ID/modifIEd" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" /> </linearLayout></linearLayout>
(5)添加ch1205Note.cs文件
using System;namespace MyDemos.SrcDemos{ class ch1205Note : java.lang.Object { public long ID { get; set; } public string Body { get; set; } public DateTime ModifIEdTime { get; set; } public ch1205Note() { ID = -1L; Body = string.Empty; } public ch1205Note(long ID,string body,DateTime modifIEd) { ID = ID; Body = body; ModifIEdTime = modifIEd; } public overrIDe string ToString() { return ModifIEdTime.ToString(); } }}
(6)添加ch1205linedEditText.cs文件
using AndroID.Content;using AndroID.Runtime;using AndroID.Widget;using AndroID.Graphics;using AndroID.Util;namespace MyDemos.SrcDemos{ [Register("MyDemos.SrcDemos.ch1205linedEditText")] class ch1205linedEditText : EditText { private Rect rect; private Paint paint; // 为了LayoutInflater需要提供此构造函数 public ch1205linedEditText(Context context,IAttributeSet attrs) : base(context,attrs) { rect = new Rect(); paint = new Paint(); paint.SetStyle(AndroID.Graphics.Paint.Style.@R_404_5283@); paint.color = color.lightGray; } protected overrIDe voID OnDraw(Canvas canvas) { int count = lineCount; for (int i = 0; i < count; i++) { int baseline = GetlineBounds(i,rect); canvas.Drawline(rect.left,baseline + 1,rect.Right,paint); } base.OnDraw(canvas); } }}
(7)添加ch1205NoteRepository.cs文件
using System;using System.Collections.Generic;using Mono.Data.sqlite;namespace MyDemos.SrcDemos{ class ch1205NoteRepository { private static string db_file = "notes.db3"; private static sqliteConnection GetConnection() { var dbPath = System.IO.Path.Combine( System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal),db_file); bool exists = System.IO.file.Exists(dbPath); if (!exists) sqliteConnection.Createfile(dbPath); var conn = new sqliteConnection("Data Source=" + dbPath); if (!exists) CreateDatabase(conn); return conn; } private static voID CreateDatabase(sqliteConnection connection) { var sql = "CREATE table ITEMS (ID INTEGER PRIMARY KEY autoINCREMENT,Body ntext,ModifIEd datetime);"; connection.open(); using (var cmd = connection.CreateCommand()) { cmd.CommandText = sql; cmd.ExecuteNonquery(); } // Create a sample note to get the user started sql = "INSERT INTO ITEMS (Body,ModifIEd) VALUES (@Body,@ModifIEd);"; using (var cmd = connection.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AdDWithValue("@Body","今天有个约会"); cmd.Parameters.AdDWithValue("@ModifIEd",DateTime.Now); cmd.ExecuteNonquery(); } connection.Close(); } public static IEnumerable<ch1205Note> GetAllNotes() { var sql = "SELECT * FROM ITEMS;"; using (var conn = GetConnection()) { conn.open(); using (var cmd = conn.CreateCommand()) { cmd.CommandText = sql; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { yIEld return new ch1205Note( reader.GetInt32(0),reader.GetString(1),reader.GetDateTime(2)); } } } } } public static ch1205Note GetNote(long ID) { var sql = "SELECT * FROM ITEMS WHERE ID = ID;"; using (var conn = GetConnection()) { conn.open(); using (var cmd = conn.CreateCommand()) { cmd.CommandText = sql; using (var reader = cmd.ExecuteReader()) { if (reader.Read()) return new ch1205Note(reader.GetInt32(0),reader.GetDateTime(2)); else return null; } } } } public static voID DeleteNote(ch1205Note note) { var sql = string.Format("DELETE FROM ITEMS WHERE ID = {0};",note.ID); using (var conn = GetConnection()) { conn.open(); using (var cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.ExecuteNonquery(); } } } public static voID SaveNote(ch1205Note note) { using (var conn = GetConnection()) { conn.open(); using (var cmd = conn.CreateCommand()) { if (note.ID < 0) { // Do an insert cmd.CommandText = "INSERT INTO ITEMS (Body,@ModifIEd); SELECT last_insert_rowID();"; cmd.Parameters.AdDWithValue("@Body",note.Body); cmd.Parameters.AdDWithValue("@ModifIEd",DateTime.Now); note.ID = (long)cmd.ExecuteScalar(); } else { // Do an update cmd.CommandText = "UPDATE ITEMS SET Body = @Body,ModifIEd = @ModifIEd WHERE ID = @ID"; cmd.Parameters.AdDWithValue("@ID",note.ID); cmd.Parameters.AdDWithValue("@Body",DateTime.Now); cmd.ExecuteNonquery(); } } } } }}
(8)添加ch1205NoteAdapter.cs文件
using AndroID.App;using AndroID.Content;using AndroID.Widget;namespace MyDemos.SrcDemos{ class ch1205NoteAdapter : ArrayAdapter { private Activity activity; public ch1205NoteAdapter(Activity activity,Context context,int textVIEwResourceID,ch1205Note[] objects) : base(context,textVIEwResourceID,objects) { this.activity = activity; } public overrIDe AndroID.VIEws.VIEw GetVIEw(int position,AndroID.VIEws.VIEw convertVIEw,AndroID.VIEws.VIEwGroup parent) { //Get our object for this position var item = (ch1205Note)GetItem(position); // 如果convertVIEw不为null则重用它,否则从当前布局中填充(inflate)它。 // 由于这种方式不是每次都填充一个新的vIEw,因此可提高性能。 var vIEw = (convertVIEw ?? activity.LayoutInflater.Inflate( Resource.Layout.ch1205_Main,parent,false)) as linearLayout; vIEw.FindVIEwByID<TextVIEw>(Resource.ID.body).Text = left(item.Body.Replace("\n"," "),25); vIEw.FindVIEwByID<TextVIEw>(Resource.ID.modifIEd).Text = item.ModifIEdTime.ToString(); return vIEw; } private string left(string text,int length) { if (text.Length <= length) return text; return text.Substring(0,length); } }}
(9)添加ch1205NoteEditorActivity.cs文件
using AndroID.App;using AndroID.Content;using AndroID.OS;using AndroID.Widget;using AndroID.Content.PM;namespace MyDemos.SrcDemos{ [Activity(Label = "ch1205NoteEditorActivity",ScreenorIEntation = ScreenorIEntation.Sensor,ConfigurationChanges = ConfigChanges.KeyboardHIDden | ConfigChanges.OrIEntation)] public class ch1205NoteEditorActivity : Activity { private ch1205Note note; private EditText text_vIEw; protected overrIDe voID OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentVIEw(Resource.Layout.ch1205_NoteEditor); text_vIEw = FindVIEwByID<EditText>(Resource.ID.note); var note_ID = Intent.GetLongExtra("note_ID",-1L); if (note_ID < 0) note = new ch1205Note(); else note = ch1205NoteRepository.GetNote(note_ID); } protected overrIDe voID OnResume() { base.OnResume(); text_vIEw.SetTextKeepState(note.Body); } protected overrIDe voID OnPause() { base.OnPause(); // 如果是新建的记事本且没有内容,不保存直接返回。 if (IsFinishing && note.ID == -1 && text_vIEw.Text.Length == 0) return; // 保存记事本 note.Body = text_vIEw.Text; ch1205NoteRepository.SaveNote(note); } }}
(10)添加ch1205NotePadMain.cs文件
using System.linq;using AndroID.App;using AndroID.Content;using AndroID.OS;using AndroID.VIEws;using AndroID.Widget;namespace MyDemos.SrcDemos{ [Activity(Label = "ch1205NotePadMain")] public class ch1205NotePadMain : ListActivity { // 菜单项 public const int MenuItemDelete = Menu.First; public const int MenuItemInsert = Menu.First + 1; protected overrIDe voID OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetDefaultKeyMode(DefaultKey.Shortcut); ListVIEw.SetonCreateContextMenuListener(this); PopulateList(); } public voID PopulateList() { // 获取存放到列表中的所有记事本项 var notes = ch1205NoteRepository.GetAllNotes(); var adapter = new ch1205NoteAdapter(this,this,Resource.Layout.ch1205_Main,notes.ToArray()); listadapter = adapter; } public overrIDe bool OnCreateOptionsMenu(IMenu menu) { base.OnCreateOptionsMenu(menu); menu.Add(0,MenuItemInsert,"添加") .SetShortcut('3','a') .SetIcon(AndroID.Resource.Drawable.IcmenuAdd); return true; } public overrIDe bool OnoptionsItemSelected(IMenuItem item) { switch (item.ItemID) { case MenuItemInsert: // 通过intent添加新项 var intent = new Intent(this,typeof(ch1205NoteEditorActivity)); intent.PutExtra("note_ID",-1L); StartActivityForResult(intent,0); return true; } return base.OnoptionsItemSelected(item); } public overrIDe voID OnCreateContextMenu(IContextMenu menu,VIEw vIEw,IContextMenuContextMenuInfo menuInfo) { var info = (AdapterVIEw.AdapterContextMenuInfo)menuInfo; var note = (ch1205Note)listadapter.GetItem(info.position); menu.Add(0,MenuItemDelete,"删除"); } public overrIDe bool OnContextItemSelected(IMenuItem item) { var info = (AdapterVIEw.AdapterContextMenuInfo)item.MenuInfo; var note = (ch1205Note)listadapter.GetItem(info.position); switch (item.ItemID) { case MenuItemDelete: // 删除该记事本项 ch1205NoteRepository.DeleteNote(note); PopulateList(); return true; } return false; } protected overrIDe voID OnListItemClick(ListVIEw l,VIEw v,int position,long ID) { var selected = (ch1205Note)listadapter.GetItem(position); // 执行activity,查看/编辑当前选中的项 var intent = new Intent(this,typeof(ch1205NoteEditorActivity)); intent.PutExtra("note_ID",selected.ID); StartActivityForResult(intent,0); } protected overrIDe voID OnActivityResult(int requestCode,Result resultCode,Intent data) { base.OnActivityResult(requestCode,resultCode,data); // 当列表项发生变化时,这里仅关心如何刷新它,并没有处理选定的项 PopulateList(); } }}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
总结以上是内存溢出为你收集整理的Android利用Intent实现记事本功能(NotePad)全部内容,希望文章能够帮你解决Android利用Intent实现记事本功能(NotePad)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)