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";public NoteDatabase(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<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;@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
<?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.Toolbarandroid: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"/><EditTextandroid: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 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<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 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
<?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"><TextViewandroid: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"/><TextViewandroid: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 登錄界面
哈哈界面隨自己走各位別噴
5.2筆記界面
之前自己寫的
5.3 增加記錄
5.4刪除記錄
在主界面那個刪除是刪除全部會提示你 然后你點擊進去之后還有一個刪除那條記錄的刪除鍵 這里就不做演示了
5.5 查找記錄
哈哈
##5.6 改記錄
改之前
改之后可以看到時間變化
其它效果靠這樣演示不出來,源碼在下面可以自取
5.6源碼
上面給的代碼不全 https://github.com/xiekangssq/local.git
有任何需要的可以私聊QQ 1833226220
總結
1.有寫的各位看起來不適應的可以 評論指導
2.接觸android也只有一個月時間 靠著在b站上和up主:344942458 他所制作的視頻進行了學習 講的很細致易懂各位可以去看看
總結
以上是生活随笔為你收集整理的Android安卓备忘录(笔记)大作业简单实现有源码注释详细的全部內容,希望文章能夠幫你解決所遇到的問題。