这篇文章主要介绍了Android如何实现备忘录,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
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; } } //携带数据 }
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); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://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); } //删除笔记 }
<?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: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.6 改记录
改之前
改之后可以看到时间变化
其它效果靠这样演示不出来,源码在下面可以自取
感谢你能够认真阅读完这篇文章,希望小编分享的“Android如何实现备忘录”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。