The example of this article for you to share the intent how to achieve a simple Notepad function of the demonstration process for your reference, the specific content as follows
1, run the screenshot
Clicking "..." in the upper-right corner will pop up the Add menu item, and a record will pop up the shortcut menu "Delete" item.
2. Main design Steps
(1) Adding references
Right-click "Reference" to "Add Reference" and check "System.Data" and "System.Data.SQlite" in the pop-up window, as shown in the following illustration:
Note: You do not need to add SQLite packages through NuGet, just add them in this way.
(2) Add picture
Find App_notes.png in the sample Notepad example of the Android SDK API 23, add it to the project, and swap it for ch12_app_notes.png.
(3) Add Ch1205_noteeditor.axml file
<?xml version= "1.0" encoding= "Utf-8"?> <view xmlns:android=
"http://schemas.android.com/apk/res/" Android "
class=" MyDemos.SrcDemos.ch1205LinedEditText "
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) Add Ch1205_main.axml file
<?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) Add Ch1205Note.cs file
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) Add Ch1205LinedEditText.cs file
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;
For layoutinflater you need to provide this constructor public
ch1205linededittext (context, Iattributeset attrs)
: Base ( Context, Attrs)
{
rect = new rect ();
Paint = new paint ();
Paint. SetStyle (Android.Graphics.Paint.Style.Stroke);
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, Baseline + 1, paint);
Base. OnDraw (canvas);}}
(7) Add Ch1205NoteRepository.cs file
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", "there is an appointment today");
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.GetString(1), 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) VALUES (@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", note.Body);
cmd.Parameters.AddWithValue("@Modified", DateTime.Now);
cmd.ExecuteNonQuery();
}
}
}
}
}
}
(8) Add Ch1205NoteAdapter.cs file
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);
//Reuse convertview if it is not null, otherwise populate it from the current layout.
//Because this approach does not fill in a new view every time, performance can be improved.
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) Add Ch1205NoteEditorActivity.cs file
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 it is a new notepad and there is no content, it will be returned without saving.
if (IsFinishing && note.Id == -1 && text_view.Text.Length == 0)
Return;
//Keep Notepad
note.Body = text_view.Text;
ch1205NoteRepository.SaveNote(note);
}
}
}
(10) Add Ch1205NotePadMain.cs file
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
{
/ / menu item
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()
{
//Get all Notepad items stored in the list
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, 0, "add")
.SetShortcut('3', 'a')
.SetIcon(Android.Resource.Drawable.IcMenuAdd);
Return true;
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
Case menuiteminsert: / / add a new item through 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, 0, delete);
}
public override bool OnContextItemSelected(IMenuItem item)
{
var info = (AdapterView.AdapterContextMenuInfo)item.MenuInfo;
var note = (ch1205Note)ListAdapter.GetItem(info.Position);
switch (item.ItemId)
{
Case menuitemdelete: / / delete the Notepad item
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);
//Execute activity to view / edit the currently selected item
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);
//When the list item changes, we only care about how to refresh it, not the selected item
PopulateList();
}
}
}
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.