Android利用Intent實(shí)現(xiàn)記事本功能(NotePad)
本文實(shí)例為大家分享了Intent如何實(shí)現(xiàn)一個(gè)簡單的記事本功能的演示過程,供大家參考,具體內(nèi)容如下
1、運(yùn)行截圖
單擊右上角【…】會(huì)彈出【添加】菜單項(xiàng),長按某條記錄會(huì)彈出快捷菜單【刪除】項(xiàng)。

2、主要設(shè)計(jì)步驟
(1)添加引用
鼠標(biāo)右擊【引用】à【添加引用】,在彈出的窗口中勾選“System.Data”和“System.Data.SQlite”,如下圖所示:

注意:不需要通過NuGet添加SQLite程序包,只需要按這種方式添加即可。
(2)添加圖片
到Android SDK API 23的Samples的NotePad例子下找到app_notes.png,將其添加到該項(xiàng)目中,并將其換名為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" 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)添加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需要提供此構(gòu)造函數(shù)
public ch1205LinedEditText(Context 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)添加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", "今天有個(gè)約會(huì)");
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)添加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則重用它,否則從當(dāng)前布局中填充(inflate)它。
// 由于這種方式不是每次都填充一個(gè)新的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();
// 如果是新建的記事本且沒有內(nèi)容,不保存直接返回。
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
{
// 菜單項(xiàng)
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()
{
// 獲取存放到列表中的所有記事本項(xiàng)
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, "添加")
.SetShortcut('3', 'a')
.SetIcon(Android.Resource.Drawable.IcMenuAdd);
return true;
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
case MenuItemInsert: // 通過intent添加新項(xiàng)
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, "刪除");
}
public override bool OnContextItemSelected(IMenuItem item)
{
var info = (AdapterView.AdapterContextMenuInfo)item.MenuInfo;
var note = (ch1205Note)ListAdapter.GetItem(info.Position);
switch (item.ItemId)
{
case MenuItemDelete: // 刪除該記事本項(xiàng)
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);
// 執(zhí)行activity,查看/編輯當(dāng)前選中的項(xiàng)
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);
// 當(dāng)列表項(xiàng)發(fā)生變化時(shí),這里僅關(guān)心如何刷新它,并沒有處理選定的項(xiàng)
PopulateList();
}
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android實(shí)現(xiàn)簡易記事本
- Android實(shí)現(xiàn)記事本小功能
- Android記事本項(xiàng)目開發(fā)
- Android實(shí)現(xiàn)記事本功能
- Android實(shí)現(xiàn)簡易記事本
- android實(shí)現(xiàn)記事本app
- Android+SQLite數(shù)據(jù)庫實(shí)現(xiàn)的生詞記事本功能實(shí)例
- Android中實(shí)現(xiàn)記事本動(dòng)態(tài)添加行效果
- Android實(shí)現(xiàn)記事本功能(26)
- Android手機(jī)開發(fā)設(shè)計(jì)之記事本功能
相關(guān)文章
Android中 webView調(diào)用JS出錯(cuò)的解決辦法
這篇文章主要介紹了Android中 webView調(diào)用JS出錯(cuò)的解決辦法,需要的朋友可以參考下2015-01-01
Android使用 Coroutine + Retrofit打造簡單的HTTP請求庫
這篇文章主要介紹了Android使用 Coroutine + Retrofit打造簡單的HTTP請求庫,幫助大家更好的理解和學(xué)習(xí)使用Android,感興趣的朋友可以了解下2021-03-03
Android給scrollView截圖超過屏幕大小形成長圖
這篇文章主要為大家詳細(xì)介紹了Android給scrollView截圖超過屏幕大小形成長圖,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12
RecyclerView實(shí)現(xiàn)抖音縱向滾動(dòng)ViewPager效果
這篇文章主要為大家詳細(xì)介紹了RecyclerView實(shí)現(xiàn)抖音縱向滾動(dòng)ViewPager效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07
Android notifyDataSetChanged() 動(dòng)態(tài)更新ListView案例詳解
這篇文章主要介紹了Android notifyDataSetChanged() 動(dòng)態(tài)更新ListView案例詳解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
Android自定義View Flyme6的Viewpager指示器
這篇文章主要為大家詳細(xì)介紹了Android自定義View Flyme6的Viewpager指示器,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01
android在連拍菜單中增加連拍張數(shù)選項(xiàng)功能實(shí)現(xiàn)代碼
想要增加連拍張數(shù)選項(xiàng)需要在entries, entryvalues中添加兩項(xiàng),同時(shí)在mtk_strings.xml中添加相應(yīng)的字符串,具體如下,感興趣的朋友可以參考下哈2013-06-06

