今天实现一个日常中大家可能会使用到的功能—日记本,也可以说是备忘录,并已实现兼容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()