android开发分享Android 备忘录的实现流程详解

目录一、首先创建保存数据的表二、主界面2.1 activity_main.xml三、:editactivity.java3.1 edit_layout.xml四、对笔记进行增删查改4.1 note_l

目录
  • 一、首先创建保存数据的表
  • 二、主界面
    • 2.1 activity_main.xml
  • 三、:editactivity.java
    • 3.1 edit_layout.xml
  • 四、对笔记进行增删查改
    • 4.1 note_layout.xml
  • 五、演示效果
    • 5.1 登录界面
    • 5.2笔记界面
    • 5.3 增加记录
    • 5.4删除记录
    • 5.5 查找记录
    • 5.6源码
  • 总结

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

    上述就是android开发分享Android 备忘录的实现流程详解的全部内容,如果对大家有所用处且需要了解更多关于Android学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

    一、首先创建保存数据的表

    notedatabase,java

      package com.example.biji_1;  import android.content.context;  import android.database.sqlite.sqlitedatabase;  import android.database.sqlite.sqliteopenhelper;  public class notedatabase extends sqliteopenhelper {      public static final string table_name ="notes";      public static final string content ="content";      public static final string id ="_id";      public static final string time ="time";      public static final string mode ="mode";      public  notedatabase(context context){          super(context,"notes",null,1);      }      @override      public void oncreate(sqlitedatabase db){          db.execsql("create table " + table_name + "(" + id                  + " integer primary key autoincrement, "                  + content + " text not null, "                  + time + " text not null, "                  + mode + " integer default 1)");      }      @override      public void onupgrade(sqlitedatabase db, int oldversion,int newversion){      }  }    

    二、主界面

    mainacitivity.java

      public class mainactivity extends baseactivity implements adapterview.onitemclicklistener {      //test gittt      private notedatabase dbhelper;      private context context = this;      final string tag = "tag";      floatingactionbutton btn;      private listview lv;      private noteadapter adapter;      private list<note> notelist = new arraylist<note>();      private toolbar mytoolbar;      //弹出菜单      private popupwindow popupwindow;      private popupwindow popupcover;      private viewgroup customview;      private viewgroup coverview;      private layoutinflater layoutinflater;      private relativelayout main;      private windowmanager wm;      private displaymetrics metrics;      private textview setting_text;      private imageview setting_image;        @override      protected void oncreate(bundle savedinstancestate){          super.oncreate(savedinstancestate);          setcontentview(r.layout.activity_main);          initprefs();          btn = (floatingactionbutton) findviewbyid(r.id.fab);          lv = findviewbyid(r.id.lv);            mytoolbar = findviewbyid(r.id.mytoolbar);          adapter = new noteadapter(getapplicationcontext(), notelist);          refreshlistview();          lv.setadapter(adapter);            setsupportactionbar(mytoolbar);          getsupportactionbar().sethomebuttonenabled(true);          getsupportactionbar().setdisplayhomeasupenabled(true); //设置toolbar取代actionbar          initpopupview();          mytoolbar.setnavigationicon(r.drawable.ic_baseline_menu_24);          mytoolbar.setnavigationonclicklistener(new view.onclicklistener() {              @override              public void onclick(view v) {                  log.d(tag, "onclick: shit");                  showpopupview();              }          });            lv.setonitemclicklistener(this);            btn.setonclicklistener(new view.onclicklistener() {              @override              public void onclick(view v) {                  intent intent = new intent(mainactivity.this, editactivity.class);                  intent.putextra("mode", 4);                  startactivityforresult(intent, 0);              }          });        }      public void initpopupview(){          layoutinflater = (layoutinflater) mainactivity.this.getsystemservice(context.layout_inflater_service);          customview = (viewgroup) layoutinflater.inflate(r.layout.setting_layout, null);          coverview = (viewgroup) layoutinflater.inflate(r.layout.setting_cover, null);          main = findviewbyid(r.id.main_layout);          wm = getwindowmanager();          metrics = new displaymetrics();          wm.getdefaultdisplay().getmetrics(metrics);      }      public void showpopupview(){          int width = metrics.widthpixels;          int height = metrics.heightpixels;            popupcover = new popupwindow(coverview, width, height, false);          popupwindow = new popupwindow(customview, (int) (width * 0.7), height, true);          popupwindow.setbackgrounddrawable(new colordrawable(color.white));              //在主界面加载成功之后 显示弹出          findviewbyid(r.id.main_layout).post(new runnable() {              @override              public void run() {                  popupcover.showatlocation(main, gravity.no_gravity, 0, 0);                  popupwindow.showatlocation(main, gravity.no_gravity, 0, 0);                    setting_image = customview.findviewbyid(r.id.setting_settings_image);                  setting_text = customview.findviewbyid(r.id.setting_settings_text);                    setting_image.setonclicklistener(new view.onclicklistener() {                      @override                      public void onclick(view v) {                          startactivity(new intent(mainactivity.this, usersettingsactivity.class));                      }                  });                    setting_text.setonclicklistener(new view.onclicklistener() {                      @override                      public void onclick(view v) {                          startactivity(new intent(mainactivity.this, usersettingsactivity.class));                      }                  });                    coverview.setontouchlistener(new view.ontouchlistener() {                      @override                      public boolean ontouch(view v, motionevent event) {                          popupwindow.dismiss();                          return true;                      }                  });                    popupwindow.setondismisslistener(new popupwindow.ondismisslistener() {                      @override                      public void ondismiss() {                          popupcover.dismiss();                          log.d(tag, "ondismiss: test");                      }                  });              }            });        }      public void initprefs(){          sharedpreferences sharedpreferences = preferencemanager.getdefaultsharedpreferences(getbasecontext());          sharedpreferences.editor editor = sharedpreferences.edit();          if (!sharedpreferences.contains("nightmode")) {              editor.putboolean("nightmode", false);              editor.commit();          }      }      // 接受startactivityforresult的结果      @override      protected void onactivityresult(int requestcode, int resultcode, intent data){            int returnmode;          long note_id;          returnmode = data.getextras().getint("mode", -1);          note_id = data.getextras().getlong("id", 0);              if (returnmode == 1) {  //update current note                string content = data.getextras().getstring("content");              string time = data.getextras().getstring("time");              int tag = data.getextras().getint("tag", 1);                note newnote = new note(content, time, tag);              newnote.setid(note_id);              crud op = new crud(context);              op.open();              op.updatenote(newnote);              op.close();          } else if (returnmode == 0) {  // create new note              string content = data.getextras().getstring("content");              string time = data.getextras().getstring("time");              int tag = data.getextras().getint("tag", 1);                note newnote = new note(content, time, tag);              crud op = new crud(context);              op.open();              op.addnote(newnote);              op.close();          } else if (returnmode == 2) { // delete              note curnote = new note();              curnote.setid(note_id);              crud op = new crud(context);              op.open();              op.removenote(curnote);              op.close();          }          else{            }          refreshlistview();          super.onactivityresult(requestcode, resultcode, data);        }  //判断笔记状态      @override      public boolean oncreateoptionsmenu(menu menu) {          getmenuinflater().inflate(r.menu.main_menu, menu);            //search setting          menuitem msearch = menu.finditem(r.id.action_search);          searchview msearchview = (searchview) msearch.getactionview();            msearchview.setqueryhint("请输入搜索内容");          msearchview.setonquerytextlistener(new searchview.onquerytextlistener() {              @override              public boolean onquerytextsubmit(string query) {                  return false;              }                @override              public boolean onquerytextchange(string newtext) {                  adapter.getfilter().filter(newtext);                  return false;              }          });            return super.oncreateoptionsmenu(menu);      }   //搜索      @override      public boolean onoptionsitemselected(menuitem item){          switch (item.getitemid()){              case r.id.menu_clear:                  new alertdialog.builder(mainactivity.this)                          .setmessage("删除全部吗?")                          .setpositivebutton(android.r.string.yes, new dialoginterface.onclicklistener() {                              @override                              public void onclick(dialoginterface dialog, int which) {                                  dbhelper = new notedatabase(context);                                  sqlitedatabase db = dbhelper.getwritabledatabase();                                  db.delete("notes", null, null);                                  db.execsql("update sqlite_sequence set seq=0 where name='notes'");                                  refreshlistview();                              }                          }).setnegativebutton(android.r.string.no, new dialoginterface.onclicklistener() {                      @override                      public void onclick(dialoginterface dialog, int which) {                          dialog.dismiss();                      }                  }).create().show();                  break;            }          return super.onoptionsitemselected(item);      }  //主界面删除      public void refreshlistview(){            crud op = new crud(context);          op.open();          // set adapter          if (notelist.size() > 0) notelist.clear();          notelist.addall(op.getallnotes());          op.close();          adapter.notifydatasetchanged();      }  //刷新list      @override      public void onitemclick(adapterview<?> parent, view view, int position, long id) {          switch (parent.getid()) {              case r.id.lv:                  note curnote = (note) parent.getitematposition(position);                  intent intent = new intent(mainactivity.this, editactivity.class);                  intent.putextra("content", curnote.getcontent());                  intent.putextra("id", curnote.getid());                  intent.putextra("time", curnote.gettime());                  intent.putextra("mode", 3);     // mode of 'click to edit'                  intent.putextra("tag", curnote.gettag());                  startactivityforresult(intent, 1);      //collect data from edit                  log.d(tag, "onitemclick: " + position);                  break;          }      } //携带数据  }    

    2.1 activity_main.xml

    三、:editactivity.java

      package com.example.biji_1;  import android.content.dialoginterface;  import android.content.intent;  import android.os.bundle;  import android.util.log;  import android.view.keyevent;  import android.view.menu;  import android.view.menuitem;  import android.view.view;  import android.widget.edittext;    import androidx.appcompat.app.alertdialog;  import androidx.appcompat.widget.toolbar;    import java.text.simpledateformat;  import java.util.date;  public class editactivity extends baseactivity {      edittext et;      private toolbar mytoolbar;      private string old_content = "";      private string old_time = "";      private int old_tag = 1;      private long id = 0;      private int openmode = 0;      private int tag = 1;      public intent intent = new intent(); // message to be sent      private boolean tagchange = false;      private final string tag = "tag";      @override      protected void oncreate(bundle savedinstancestate) {          super.oncreate(savedinstancestate);          setcontentview(r.layout.edit_layout);            mytoolbar = findviewbyid(r.id.mytoolbar);          setsupportactionbar(mytoolbar);          getsupportactionbar().sethomebuttonenabled(true);          getsupportactionbar().setdisplayhomeasupenabled(true); //设置toolbar取代actionbar            mytoolbar.setnavigationonclicklistener(new view.onclicklistener() {              @override              public void onclick(view view) {                  autosetmessage();                  setresult(result_ok, intent);                  finish();                }          });                mytoolbar.setnavigationonclicklistener(new view.onclicklistener() {              @override              public void onclick(view v) {                  autosetmessage();                  setresult(result_ok, intent);                  finish();              }          });          et = findviewbyid(r.id.et_1);          intent getintent = getintent();          openmode = getintent.getintextra("mode", 0);            if (openmode == 3) {//打开已存在的note              id = getintent.getlongextra("id", 0);              old_content = getintent.getstringextra("content");              old_time = getintent.getstringextra("time");              old_tag = getintent.getintextra("tag", 1);              et.settext(old_content);              et.setselection(old_content.length());              log.d("tag","打开");            }      }      //渲染菜单栏      @override      public boolean oncreateoptionsmenu(menu menu_1) {          getmenuinflater().inflate(r.menu.edit_menu,menu_1);          return super.oncreateoptionsmenu(menu_1);      }      @override      public boolean onoptionsitemselected(menuitem item){          switch (item.getitemid()){              case r.id.delete:                  new alertdialog.builder(editactivity.this)                          .setmessage("删除吗?")                          .setpositivebutton(android.r.string.yes, new dialoginterface.onclicklistener() {                              @override                              public void onclick(dialoginterface dialog, int which) {                                  if (openmode == 4){ // new note                                      intent.putextra("mode", -1);                                      setresult(result_ok, intent);                                  }                                  else { // existing note                                      intent.putextra("mode", 2);                                      intent.putextra("id", id);                                      setresult(result_ok, intent);                                  }                                  finish();                              }                          }).setnegativebutton(android.r.string.no, new dialoginterface.onclicklistener() {                      @override                      public void onclick(dialoginterface dialog, int which) {                          dialog.dismiss();                      }                  }).create().show();                  break;          }          return super.onoptionsitemselected(item);      }      public boolean onkeydown(int keycode, keyevent event){          if (keycode == keyevent.keycode_home){              return true;          }          else if (keycode == keyevent.keycode_back){              autosetmessage();              setresult(result_ok, intent);              finish();              return true;          }          return super.onkeydown(keycode, event);      }      public void autosetmessage(){          if(openmode == 4){              if(et.gettext().tostring().length() == 0){                  intent.putextra("mode", -1); //nothing new happens.              }              else{                  intent.putextra("mode", 0); // new one note;                  intent.putextra("content", et.gettext().tostring());                  intent.putextra("time", datetostr());                  intent.putextra("tag", tag);              }          }          else {              if (et.gettext().tostring().equals(old_content) && !tagchange)                  intent.putextra("mode", -1); // edit nothing              else {                  intent.putextra("mode", 1); //edit the content                  intent.putextra("content", et.gettext().tostring());                  intent.putextra("time", datetostr());                  intent.putextra("id", id);                  intent.putextra("tag", tag);              }          }      }      public string datetostr(){          date date = new date();          simpledateformat simpledateformat = new simpledateformat("yyyy-mm-dd hh:mm:ss");          return simpledateformat.format(date);      }  }  

    3.1 edit_layout.xml

      <?xml version="1.0" encoding="utf-8"?>  <linearlayout xmlns:android="https://schemas.android.com/apk/res/android"      xmlns:app="https://schemas.android.com/apk/res-auto"      android:orientation="vertical"      android:layout_width="match_parent"      android:layout_height="match_parent">      <androidx.appcompat.widget.toolbar          android:id="@+id/mytoolbar"          android:layout_width="match_parent"          android:layout_height="?attr/actionbarsize"          android:elevation="4dp"          app:titletextcolor="#ffebcd"          app:popuptheme="@style/themeoverlay.appcompat.light"          />      <edittext          android:id="@+id/et_1"          android:layout_width="match_parent"          android:layout_height="100dp"          android:gravity="top"          />    </linearlayout>  

    四、对笔记进行增删查改

    crud.java

      package com.example.biji_1;    import android.annotation.suppresslint;  import android.content.contentvalues;  import android.content.context;  import android.database.cursor;  import android.database.sqlite.sqlitedatabase;  import android.database.sqlite.sqliteopenhelper;    import java.util.arraylist;  import java.util.list;    public class crud {      sqliteopenhelper dbhandler;      sqlitedatabase db;        private static final string[] columns = {              notedatabase.id,              notedatabase.content,              notedatabase.time,              notedatabase.mode      };        public crud(context context){          dbhandler = new notedatabase(context);      }        public void open(){          db = dbhandler.getwritabledatabase();      }        public void close(){          dbhandler.close();      }        //把note 加入到database里面      public note addnote(note note){          //add a note object to database          contentvalues contentvalues = new contentvalues();          contentvalues.put(notedatabase.content, note.getcontent());          contentvalues.put(notedatabase.time, note.gettime());          contentvalues.put(notedatabase.mode, note.gettag());          long insertid = db.insert(notedatabase.table_name, null, contentvalues);          note.setid(insertid);          return note;      }        public note getnote(long id){          //get a note from database using cursor index          cursor cursor = db.query(notedatabase.table_name,columns,notedatabase.id + "=?",                  new string[]{string.valueof(id)},null,null, null, null);          if (cursor != null) cursor.movetofirst();          note e = new note(cursor.getstring(1),cursor.getstring(2), cursor.getint(3));          return e;      }        @suppresslint("range")      public list<note> getallnotes(){          cursor cursor = db.query(notedatabase.table_name,columns,null,null,null, null, null);            list<note> notes = new arraylist<>();          if(cursor.getcount() > 0){              while(cursor.movetonext()){                  note note = new note();                  note.setid(cursor.getlong(cursor.getcolumnindex(notedatabase.id)));                  note.setcontent(cursor.getstring(cursor.getcolumnindex(notedatabase.content)));                  note.settime(cursor.getstring(cursor.getcolumnindex(notedatabase.time)));                  note.settag(cursor.getint(cursor.getcolumnindex(notedatabase.mode)));                  notes.add(note);              }          }          return notes;      } //查找笔记        public int updatenote(note note) {          //update the info of an existing note          contentvalues values = new contentvalues();          values.put(notedatabase.content, note.getcontent());          values.put(notedatabase.time, note.gettime());          values.put(notedatabase.mode, note.gettag());          // updating row          return db.update(notedatabase.table_name, values,                  notedatabase.id + "=?",new string[] { string.valueof(note.getid())});      } //更新笔记        public void removenote(note note) {          //remove a note according to id value          db.delete(notedatabase.table_name, notedatabase.id + "=" + note.getid(), null);      }  //删除笔记  }  

    4.1 note_layout.xml

      <?xml version="1.0" encoding="utf-8"?>  <linearlayout xmlns:android="https://schemas.android.com/apk/res/android"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:paddingleft="10dp"      android:paddingright="10dp"      android:paddingtop="5dp"      android:paddingbottom="12dp"      android:orientation="vertical"      android:background="@drawable/note_shape">          <textview          android:id="@+id/tv_content"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:text="content"          android:textsize="20dp"          android:textcolor="	#00f5ff"          android:singleline="true"          />        <textview          android:id="@+id/tv_time"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:text="time"          android:textsize="16dp"          android:textcolor="	#00f5ff"/>      </linearlayout>  

    五、演示效果

    5.1 登录界面

    Android 备忘录的实现流程详解

    哈哈界面随自己走各位别喷

    5.2笔记界面

    Android 备忘录的实现流程详解

    之前自己写的

    5.3 增加记录

    Android 备忘录的实现流程详解

    Android 备忘录的实现流程详解

    5.4删除记录

    Android 备忘录的实现流程详解

    在主界面那个删除是删除全部会提示你 然后你点击进去之后还有一个删除那条记录的删除键 这里就不做演示了

    5.5 查找记录

    Android 备忘录的实现流程详解

    哈哈
    ##5.6 改记录

    Android 备忘录的实现流程详解

    改之前

    Android 备忘录的实现流程详解

    改之后可以看到时间变化

    其它效果靠这样演示不出来,源码在下面可以自取

    5.6源码

    上面给的代码不全 https://github.com/xiekangssq/local.git

    总结

    有写的各位看起来不适应的可以 评论指导

    到此这篇关于android 备忘录的实现流程详解的文章就介绍到这了,更多相关android 备忘录内容请搜索<计算机技术网(www.ctvol.com)!!>以前的文章或继续浏览下面的相关文章希望大家以后多多支持<计算机技术网(www.ctvol.com)!!>!

    本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

    ctvol管理联系方式QQ:251552304

    本文章地址:https://www.ctvol.com/addevelopment/937575.html

    (0)
    上一篇 2021年11月12日
    下一篇 2021年11月12日

    精彩推荐