Android|Android 备忘录的实现流程详解

目录

  • 一、首先创建保存数据的表
  • 二、主界面
    • 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源码
  • 总结
    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

    一、首先创建保存数据的表 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"; publicNoteDatabase(Context context){super(context,"notes",null,1); }@Overridepublic 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)"); }@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion,int newVersion){}}


    二、主界面 MainAcitivity.java
    public class MainActivity extends BaseActivity implements AdapterView.OnItemClickListener {//test gitttprivate NoteDatabase dbHelper; private Context context = this; final String TAG = "tag"; FloatingActionButton btn; private ListView lv; private NoteAdapter adapter; private List noteList = new ArrayList(); 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; @Overrideprotected 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取代actionbarinitPopUpView(); myToolbar.setNavigationIcon(R.drawable.ic_baseline_menu_24); myToolbar.setNavigationOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Log.d(TAG, "onClick: shit"); showPopUpView(); }}); lv.setOnItemClickListener(this); btn.setOnClickListener(new View.OnClickListener() {@Overridepublic 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() {@Overridepublic 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() {@Overridepublic void onClick(View v) {startActivity(new Intent(MainActivity.this, UserSettingsActivity.class)); }}); setting_text.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {startActivity(new Intent(MainActivity.this, UserSettingsActivity.class)); }}); coverView.setOnTouchListener(new View.OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {popupWindow.dismiss(); return true; }}); popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {@Overridepublic 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的结果@Overrideprotected 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 noteString 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 noteString 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) { // deleteNote 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); }//判断笔记状态@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.main_menu, menu); //search settingMenuItem mSearch = menu.findItem(R.id.action_search); SearchView mSearchView = (SearchView) mSearch.getActionView(); mSearchView.setQueryHint("请输入搜索内容"); mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {@Overridepublic boolean onQueryTextSubmit(String query) {return false; }@Overridepublic boolean onQueryTextChange(String newText) {adapter.getFilter().filter(newText); return false; }}); return super.onCreateOptionsMenu(menu); }//搜索@Overridepublic 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() {@Overridepublic 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() {@Overridepublic 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 adapterif (noteList.size() > 0) noteList.clear(); noteList.addAll(op.getAllNotes()); op.close(); adapter.notifyDataSetChanged(); }//刷新list@Overridepublic 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 editLog.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 sentprivate boolean tagChange = false; private final String TAG = "tag"; @Overrideprotected 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取代actionbarmyToolbar.setNavigationOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {autoSetMessage(); setResult(RESULT_OK, intent); finish(); }}); myToolbar.setNavigationOnClickListener(new View.OnClickListener() {@Overridepublic 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) {//打开已存在的noteid = 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","打开"); }}//渲染菜单栏@Overridepublic boolean onCreateOptionsMenu(Menu menu_1) {getMenuInflater().inflate(R.menu.edit_menu,menu_1); return super.onCreateOptionsMenu(menu_1); }@Overridepublic 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() {@Overridepublic void onClick(DialogInterface dialog, int which) {if (openMode == 4){ // new noteintent.putExtra("mode", -1); setResult(RESULT_OK, intent); }else { // existing noteintent.putExtra("mode", 2); intent.putExtra("id", id); setResult(RESULT_OK, intent); }finish(); }}).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {@Overridepublic 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 nothingelse {intent.putExtra("mode", 1); //edit the contentintent.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


    四、对笔记进行增删查改 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 databaseContentValues 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 indexCursor 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 getAllNotes(){Cursor cursor = db.query(NoteDatabase.TABLE_NAME,columns,null,null,null, null, null); List 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 noteContentValues values = new ContentValues(); values.put(NoteDatabase.CONTENT, note.getContent()); values.put(NoteDatabase.TIME, note.getTime()); values.put(NoteDatabase.MODE, note.getTag()); // updating rowreturn 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 valuedb.delete(NoteDatabase.TABLE_NAME, NoteDatabase.ID + "=" + note.getId(), null); }//删除笔记}


    4.1 note_layout.xml


    五、演示效果
    5.1 登录界面
    Android|Android 备忘录的实现流程详解
    文章图片

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

    5.2笔记界面
    Android|Android 备忘录的实现流程详解
    文章图片

    之前自己写的

    5.3 增加记录
    Android|Android 备忘录的实现流程详解
    文章图片

    Android|Android 备忘录的实现流程详解
    文章图片


    5.4删除记录
    Android|Android 备忘录的实现流程详解
    文章图片

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

    5.5 查找记录
    Android|Android 备忘录的实现流程详解
    文章图片

    哈哈
    ##5.6 改记录
    Android|Android 备忘录的实现流程详解
    文章图片

    改之前
    Android|Android 备忘录的实现流程详解
    文章图片

    改之后可以看到时间变化
    其它效果靠这样演示不出来,源码在下面可以自取

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

    总结 有写的各位看起来不适应的可以 评论指导
    【Android|Android 备忘录的实现流程详解】到此这篇关于Android 备忘录的实现流程详解的文章就介绍到这了,更多相关Android 备忘录内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

      推荐阅读