当前位置: 移动技术网 > IT编程>移动开发>Android > Android实现简易记事本

Android实现简易记事本

2019年07月24日  | 移动技术网IT编程  | 我要评论

胡雯图片,扫射龙颅村,玩趣乐品

本文实例为大家分享了android实现简易记事本的具体代码,供大家参考,具体内容如下

此次做的android简易记事本的存储方式使用了sqlite数据库,然后界面的实现比较简单,但是,具有增删改查的基本功能,这里可以看一下效果图,如下:

具体操作就是长按可以删除操作,点击可以进行修改,点击添加笔记按钮可以添加一个笔记。

首先我们需要三个界面样式一个是我们的进入程序时的第一个界面,然后第一个界面里面有一个listview,这个listview需要一个xml来描述里面的各个元素,这也是第二个。还有一个就是我们的编辑页面的界面。
三个xml描述文件如下:

activity_main.xml:进入程序的第一个界面

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  tools:context=".mainactivity" >

  <textview  
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent" 
    android:text="记事本列表" 
    android:textsize="20sp" 
    android:paddingtop="10dp" 
    android:paddingbottom="5dp" 
    android:gravity="center"/> 
 
  <linearlayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_weight="1" > 
 
    <listview 
      android:id="@+id/listnote" 
      android:layout_margin="5dp" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" > 
    </listview> 
  </linearlayout> 
 
  <button 
    android:id="@+id/addnote" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center" 
    android:layout_marginbottom="10dp" 
    android:text="添加笔记" 
    android:textsize="20sp" /> 
  
</linearlayout>

note_item.xml:描述记事本列表中每个元素的各个控件

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >
  
  <textview
    android:id="@+id/notetitle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginleft="10dp"
    android:singleline="true"
    android:text=""
    android:textappearance="?android:attr/textappearancelarge" />

  <textview
    android:id="@+id/notecreatetime"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginleft="10dp"
    android:text="" />

</linearlayout>

note_editor.xml:编辑界面

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >

  <textview 
    android:id="@+id/noteid"
    android:visibility="gone"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""/>
  
  <edittext
    android:id="@+id/title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10" 
    android:hint="输入标题">
    <requestfocus />
  </edittext>
  
  <edittext
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:hint="输入内容"
    android:gravity="left">
  </edittext>
  
  <linearlayout 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_gravity="center"
    android:gravity="center">
    
    <button 
    android:id="@+id/save" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center" 
    android:layout_marginbottom="10dp" 
    android:text="保存" 
    android:textsize="20sp" /> 
    
    <button 
    android:id="@+id/cancel" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center" 
    android:layout_marginbottom="10dp" 
    android:text="取消" 
    android:textsize="20sp" /> 
  </linearlayout>

</linearlayout>

现在我们可以考虑我们底层的数据库的操作了,这里有一个类专门用于与数据库打交道,如下:
dbservice.java

public class dbservice {
  
  private static sqlitedatabase db = null;
  
  static {
    //新建或者打开db
    db = sqlitedatabase.openorcreatedatabase("data/data/cn.lger.notebook/notebook.db", null);
    
    string sql = "create table notebook(_id integer primary key autoincrement,title varchar(255),content text, createtime varchar(25))";
    
    //判断是否存在表notebook,如果不存在会抛出异常,捕捉异常后创建表
    try{
      db.rawquery("select count(1) from notebook ",null);
    }catch(exception e){
      db.execsql(sql);
    }
  }
  
  public static sqlitedatabase getsqlitedatabase(){
    return db;
  }
  
  public static cursor queryall(){
    return db.rawquery("select * from notebook ",null);
  }
  
  public static cursor querynotebyid(integer id){
    return db.rawquery("select * from notebook where _id =?",new string[]{id.tostring()});
  }
  
  public static void deletenotebyid(integer id){
    if(id == null)
      return ;
    db.delete("notebook", "_id=?", new string[]{id.tostring()});
  }
  
  public static void updatenotebyid(integer id, contentvalues values){
    db.update("notebook", values, "_id=?", new string[]{id.tostring()});
  }
  
  /**
   * 添加一个笔记,并且记录当前添加的时间
   * @param values 表中的各个字段值
   */
  public static void addnote(contentvalues values){
    values.put("createtime", dateformat.format("yyyy-mm-dd kk:mm:ss", system.currenttimemillis()).tostring());
    db.insert("notebook", null, values);
  }
}

下面我们在进入第一个界面的时候需要访问数据库并且将数据的值不断的更新(比如进行了删除操作的时候或者添加操作之后需要刷新),这样,我们就可能需要重写activity的onresume(),这样就可以调用cursor的requery()来刷新我们列表中listview的结果。还有我们需要长按删除,点击修改,添加笔记这些都需要监听事件,因此,这里还要设置监听
具体mainactivity.java的代码如下:

public class mainactivity extends activity {
  private cursor listitemcursor = null;

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);

    // 设置添加笔记按钮事件,切换activity
    this.findviewbyid(r.id.addnote).setonclicklistener(
        new onclicklistener() {
          @override
          public void onclick(view arg0) {
            intent in = new intent();
            in.setclassname(getapplicationcontext(),
                "cn.lger.notebook.noteeditactivity");
            startactivity(in);
          }
        });

    // 查询所有笔记,并将笔记展示出来
    listitemcursor = dbservice.queryall();
    simplecursoradapter adapter = new simplecursoradapter(mainactivity.this,
        r.layout.note_item, listitemcursor, new string[] { "_id",
            "title", "createtime" }, new int[] { r.id.noteid,
            r.id.notetitle, r.id.notecreatetime },
        cursoradapter.flag_register_content_observer);
    ((listview) this.findviewbyid(r.id.listnote)).setadapter(adapter);

    initlistnotelistener();

  }

  /**
   * 初始化笔记列表的长按和点击事件
   */
  private void initlistnotelistener() {
    // 长按删除
    ((listview) this.findviewbyid(r.id.listnote))
        .setonitemlongclicklistener(new onitemlongclicklistener() {

          @override
          public boolean onitemlongclick(adapterview<?> parent,
              view view, int position, final long id) {
            new alertdialog.builder(mainactivity.this)
                .settitle("提示框")
                .setmessage("确认删除该笔记??")
                .setpositivebutton("确定",
                    new dialoginterface.onclicklistener() {
                      @override
                      public void onclick(dialoginterface arg0,int arg1) {
                        dbservice.deletenotebyid((int) id);
                        //删除后刷新列表
                        mainactivity.this.onresume();
                        toast.maketext(
                            mainactivity.this,
                            "删除成功!!",
                            toast.length_long)
                            .show();
                      }
                    }).setnegativebutton("取消", null).show();
            return false;
          }
        });

    //点击进行修改操作
    ((listview) this.findviewbyid(r.id.listnote))
        .setonitemclicklistener(new onitemclicklistener() {

          @override
          public void onitemclick(adapterview<?> parent, view view,
              int position, long id) {
            intent in = new intent();
            in.setclassname(view.getcontext(),
                "cn.lger.notebook.noteeditactivity");
            // 将id数据放置到intent,切换视图后可以将数据传递过去
            in.putextra("id", id);
            startactivity(in);
          }
        });

  }

  @override
  public boolean oncreateoptionsmenu(menu menu) {
    getmenuinflater().inflate(r.menu.main, menu);
    return true;
  }

  /**
   * 当从另一个视图进入该视图会调用该方法
   */
  @override
  protected void onresume() {
    super.onresume();
    // 要求刷新主页列表笔记
    if (listitemcursor != null) {
      listitemcursor.requery();
    }
  }
}

上面的代码中还涉及到了一个视图切换后的传递信息的操作,就是通过intent的putextra(key, value)这样可以在切换后的视图中调用函数getintent().get~extra(key, replace);来接收传递的数据。

下面是我们的编辑界面中对应的具体实现代码,这里有判断是使用更新操作还是添加操作,主要是判断mainactivity.java有没有传递过来id,如果有就是通过这个id来更新操作,没有就是添加操作。

编辑界面对应的具体实现代码如下:

noteeditactivity.java

public class noteeditactivity extends activity {

  private edittext titleedittext = null;
  private edittext contentedittext = null;
  private string noteid = null;

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.note_editor);

    titleedittext = (edittext) noteeditactivity.this
        .findviewbyid(r.id.title);
    contentedittext = (edittext) noteeditactivity.this
        .findviewbyid(r.id.content);
    
    initnoteeditvalue();
    
    //取消按钮监听
    this.findviewbyid(r.id.cancel).setonclicklistener(
        new onclicklistener() {
          @override
          public void onclick(view arg0) {
            noteeditactivity.this.finish();
          }
        });

    this.findviewbyid(r.id.save).setonclicklistener(new onclicklistener() {
      @override
      public void onclick(view arg0) {

        final string title = titleedittext.gettext().tostring();
        final string content = contentedittext.gettext().tostring();
        
        //判断标题和内容是否为空,不为空才能保存
        if ("".equals(title) || "".equals(content)) {
          toast.maketext(noteeditactivity.this, "标题或者内容不能为空",
              toast.length_long).show();
          return;
        }
        
        //提示保存
        new alertdialog.builder(noteeditactivity.this)
            .settitle("提示框")
            .setmessage("确定保存笔记吗??")
            .setpositivebutton("确定",
                new dialoginterface.onclicklistener() {
                  @override
                  public void onclick(dialoginterface arg0,
                      int arg1) {
                    contentvalues values = new contentvalues();
                    values.put("title", title);
                    values.put("content", content);
                    
                    //如果noteid不为空那么就是更新操作,为空就是添加操作
                    if (null == noteid || "".equals(noteid))
                      dbservice.addnote(values);
                    else
                      dbservice.updatenotebyid(
                          integer.valueof(noteid),
                          values);
                    //结束当前activity
                    noteeditactivity.this.finish();
                    toast.maketext(noteeditactivity.this, "保存成功!!",
                        toast.length_long).show();
                  }
                }).setnegativebutton("取消", null).show();

      }
    });
  }

  /**
   * 初始化编辑页面的值(如果进入该页面时存在一个id的话),比如标题,内容。
   */
  private void initnoteeditvalue() {
    // 从intent中获取id的值
    long id = this.getintent().getlongextra("id", -1l);
    // 如果有传入id那么id!=-1
    if (id != -1l) {
      // 使用noteid保存id
      noteid = string.valueof(id);
      // 查询该id的笔记
      cursor cursor = dbservice.querynotebyid((int) id);
      if (cursor.movetofirst()) {
        // 将内容提取出来
        titleedittext.settext(cursor.getstring(1));
        contentedittext.settext(cursor.getstring(2));
      }
    }
  }

  @override
  public boolean oncreateoptionsmenu(menu menu) {
    getmenuinflater().inflate(r.menu.main, menu);
    return true;
  }
}

以上就将我们的安卓简易记事本完成了,源码已经上传github

界面采用了拿来主义,可以参考下面文章

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网