Android實現簡易版日記本notePad
阿新 • • 發佈:2021-01-07
今天實現一個日常中大家可能會使用到的功能—日記本,也可以說是備忘錄,並已實現相容androidX和深色模式。
app中使用Androidx中的Room資料庫,Room持久資料庫提供了一個SQLite抽象層,讓你訪問資料庫更加穩定,提升資料庫效能。Room資料庫幫助應用資料快取,這個快取是應用唯一的真實來源,並且允許使用者檢視應用中的關鍵資訊的一致副本。具體使用方法可檢視官網https://developer.android.google.cn/reference/androidx/room/package-summary?hl=zh-cn
資料庫簡單的實現單例和應用
@Database(entities = Note.class, version = 1)
public abstract class NotesDB extends RoomDatabase {
public abstract NotesDao notesDao();
public static final String DATABSE_NAME = "notesDb";
private static NotesDB instance;
public static NotesDB getInstance(Context context) {
if (instance == null)
instance = Room.databaseBuilder(context, NotesDB.class, DATABSE_NAME)
.allowMainThreadQueries()
.build();
return instance;
}
}
使用方法:NotesDB.getInstance(this).notesDao()
對資料庫的介面進行封裝
@Dao
public interface NotesDao {
/**
* Insert and save note to Database
*
* @param note
*/
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertNote(Note note);
/**
* Delete note
*
* @param note that will be delete
*/
@Delete
void deleteNote(Note... note);
/**
* Update note
*
* @param note the note that will be update
*/
@Update
void updateNote(Note note);
/**
* List All Notes From Database
*
* @return list of Notes
*/
@Query("SELECT * FROM notes")
List<Note> getNotes();
/**
* @param noteId note id
* @return Note
*/
@Query("SELECT * FROM notes WHERE id = :noteId")
Note getNoteById(int noteId);
/**
* Delete Note by Id from DataBase
*
* @param noteId
*/
@Query("DELETE FROM notes WHERE id = :noteId")
void deleteNoteById(int noteId);
}
應用中適配了深色模式,效果如下
深色模式使用
settings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
theme = settings.getInt(THEME_Key, R.style.AppTheme);
setTheme(theme);
開啟深色模式
settings.edit().putInt(THEME_Key, R.style.AppTheme_Dark).apply();
開啟普通模式
settings.edit().putInt(THEME_Key, R.style.AppTheme).apply();
接下來的主要功能是進行日記的編輯和儲存
功能實現
以下為儲存日記的程式碼片段
private void onSaveNote() {
String text = inputNote.getText().toString();
String title = inputTitleNote.getText().toString();
if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(text)) {
//獲取時間
String date = NoteUtils.getStringDate(); // get system time
// if exist update els crete new
if (temp == null) {
temp = new Note(title,text, date);
//寫入資料庫
dao.insertNote(temp); // create new note and inserted to database
} else {
temp.setTitle(title);
temp.setNoteText(text);
temp.setNoteDate(date);
//更新資料庫
dao.updateNote(temp); // change text and date and update note on database
}
finish(); // return to the MainActivity
}
}
寫入後的日記儲存到資料庫後顯示到列表中,列表使用的是簡單的recylerview
private void loadNotes() {
this.notes = new ArrayList<>();
List<Note> list = dao.getNotes();// get All notes from DataBase
this.notes.addAll(list);
this.adapter = new NotesAdapter(this, this.notes);
// set listener to adapter
this.adapter.setListener(this);
this.recyclerView.setAdapter(adapter);
showEmptyView();
// add swipe helper to recyclerView
swipeToDeleteHelper.attachToRecyclerView(recyclerView);
}
/**
* when no notes show msg in main_layout
*/
private void showEmptyView() {
if (notes.size() == 0) {
this.recyclerView.setVisibility(View.GONE);
findViewById(R.id.empty_notes_view).setVisibility(View.VISIBLE);
} else {
this.recyclerView.setVisibility(View.VISIBLE);
findViewById(R.id.empty_notes_view).setVisibility(View.GONE);
}
}
adapter程式碼
public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.NoteHolder> {
private Context context;
private ArrayList<Note> notes;
private NoteEventListener listener;
private boolean multiCheckMode = false;
public NotesAdapter(Context context, ArrayList<Note> notes) {
this.context = context;
this.notes = notes;
}
@NonNull
@Override
public NoteHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.note_layout, parent, false);
return new NoteHolder(v);
}
@Override
public void onBindViewHolder(NoteHolder holder, int position) {
final Note note = getNote(position);
if (note != null) {
holder.noteText.setText(note.getTitle());
holder.noteDate.setText(note.getNoteDate());
// init note click event
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
listener.onNoteClick(note);
}
});
// init note long click
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
listener.onNoteLongClick(note);
return false;
}
});
// check checkBox if note selected
if (multiCheckMode) {
holder.checkBox.setVisibility(View.VISIBLE); // show checkBox if multiMode on
holder.checkBox.setChecked(note.isChecked());
} else holder.checkBox.setVisibility(View.GONE); // hide checkBox if multiMode off
}
}
@Override
public int getItemCount() {
return notes.size();
}
private Note getNote(int position) {
return notes.get(position);
}
/**
* get All checked notes
*
* @return Array
*/
public List<Note> getCheckedNotes() {
List<Note> checkedNotes = new ArrayList<>();
for (Note n : this.notes) {
if (n.isChecked())
checkedNotes.add(n);
}
return checkedNotes;
}
class NoteHolder extends RecyclerView.ViewHolder {
TextView noteText, noteDate;
CheckBox checkBox;
public NoteHolder(View itemView) {
super(itemView);
noteDate = itemView.findViewById(R.id.note_date);
noteText = itemView.findViewById(R.id.note_text);
checkBox = itemView.findViewById(R.id.checkBox);
}
}
public void setListener(NoteEventListener listener) {
this.listener = listener;
}
public void setMultiCheckMode(boolean multiCheckMode) {
this.multiCheckMode = multiCheckMode;
if (!multiCheckMode)
for (Note note : this.notes) {
note.setChecked(false);
}
notifyDataSetChanged();
}
}
點選menu彈出提示框
new AlertDialog.Builder(MainActivity.this)
.setMessage("左滑可刪除日誌,長按可分享或刪除日誌")
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setCancelable(true)
.create().show();
左滑可刪除日誌
new AlertDialog.Builder(MainActivity.this)
.setMessage("是否刪除日誌?")
.setPositiveButton("刪除", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//刪除日記
dao.deleteNote(swipedNote);
notes.remove(swipedNote);
adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
showEmptyView();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// TODO: 28/09/2018 Undo swipe and restore swipedNote
recyclerView.getAdapter().notifyItemChanged(viewHolder.getAdapterPosition());
}
})
.setCancelable(false)
.create().show();
private void onDeleteMultiNotes() {
List<Note> chackedNotes = adapter.getCheckedNotes();
if (chackedNotes.size() != 0) {
for (Note note : chackedNotes) {
dao.deleteNote(note);
}
// refresh Notes
loadNotes();
Toast.makeText(this, chackedNotes.size() + " 日誌刪除成功 !", Toast.LENGTH_SHORT).show();
} else Toast.makeText(this, "沒有選擇日誌", Toast.LENGTH_SHORT).show();
//adapter.setMultiCheckMode(false);
}
長按日記可分享或者刪除
分享功能呼叫的是android系統的分享,呼叫方式如下
Note note = adapter.getCheckedNotes().get(0);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
String notetext ="標題:"+ note.getTitle() +"\n內容:"+ note.getNoteText() + "\n 建立時間: " +
note.getNoteDate() + "\n By :" +
getString(R.string.app_name);
share.putExtra(Intent.EXTRA_TEXT, notetext);
startActivity(share);
這個簡易版日記本notePad的app目前有這些功能,後期會根據需求有所增加,謝謝!