欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android利用Intent实现记事本功能(NotePad)

程序员文章站 2024-03-04 14:53:23
本文实例为大家分享了intent如何实现一个简单的记事本功能的演示过程,供大家参考,具体内容如下 1、运行截图 单击右上角【…】会弹出【添加】菜单项,长按某条记录会弹出...

本文实例为大家分享了intent如何实现一个简单的记事本功能的演示过程,供大家参考,具体内容如下

1、运行截图

单击右上角【…】会弹出【添加】菜单项,长按某条记录会弹出快捷菜单【删除】项。

Android利用Intent实现记事本功能(NotePad)

2、主要设计步骤

(1)添加引用

鼠标右击【引用】à【添加引用】,在弹出的窗口中勾选“system.data”和“system.data.sqlite”,如下图所示:

Android利用Intent实现记事本功能(NotePad)

注意:不需要通过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"
  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需要提供此构造函数
    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", "今天有个约会");
        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则重用它,否则从当前布局中填充(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, 0, "添加")
        .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, 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: // 删除该记事本项
          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();
    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。