简介

本文实现一个简单的笔记本app,每个笔记有标题和内容,笔记本首页可以浏览有哪些笔记和添加笔记,笔记详情页可以编辑删除笔记。
本app使用Compose + ViewModel + Room实现,阅读此文前可以先去了解这几个框架。由于使用了这些框架,我们只需不到300行代码即可实现我们的记事本app。
整个app结构如下:
Compose - Activity - ViewModel - Repository - RoomDatabase

数据库

首先使用room来定义我们的数据库。
我们只需要存储笔记,每个笔记有标题和内容,其实体定义如下:

@Entity
data class Note(@PrimaryKey(autoGenerate = true) val id: Long,val title: String,val content: String,
) : Serializable

接下来是定义我们的dao:

@Dao
interface NoteDao {@Insertsuspend fun insert(note: Note): Long@Insertsuspend fun insertAll(vararg note: Note)@Updatesuspend fun update(note: Note)@Deletesuspend fun delete(note: Note)@Query("DELETE FROM Note")suspend fun deleteAll()@Query("SELECT * FROM Note")fun getAll(): Flow<List<Note>>
}

虽然NoteDao只是一个interface,但是有@Dao注解,room会为我们自动实现具体方法。

然后定义我们的数据库:

@Database(entities = [Note::class], version = 1)
abstract class NoteDatabase : RoomDatabase() {abstract fun noteDao(): NoteDaocompanion object {@Volatileprivate var INSTANCE: NoteDatabase? = nullfun getInstance(context: Context, scope: CoroutineScope): NoteDatabase {return INSTANCE ?: synchronized(this) {val instance = Room.databaseBuilder(context.applicationContext,NoteDatabase::class.java,"note_database").build()INSTANCE = instanceinstance}}}
}

数据库是单例模式,确保同一个进程只创建一个NoteDatabase对象。

存储库

数据库定义完成后,就可以创建我们的存储库了,存储库十分简单,定义如下:

class NoteRepository(private val noteDao: NoteDao) {val allNotes: Flow<List<Note>> = noteDao.getAll()suspend fun insert(note: Note): Long {return noteDao.insert(note)}suspend fun update(note: Note) {return noteDao.update(note)}suspend fun delete(note: Note) {return noteDao.delete(note)}
}

有了存储库,ViewModel就可以通过存储库访问数据库了。

可能大家会有疑问为什么需要存储库,ViewModel直接访问dao来访问数据库不就可以了吗?
其实存储库这层一般还是有意义的,其可以给所有数据源提供统一接口,例如有的数据可能来自于网络。所以存储库的意义在于上层可以统一通过存储库来访问不同来源的数据。

ViewModel

有了存储库,我们就可以创建我们的ViewModel了,其定义如下:

class NoteViewModel(private val noteRepository: NoteRepository) : ViewModel() {val allNotes: LiveData<List<Note>> = noteRepository.allNotes.asLiveData()fun insertBlock(note: Note): Note = runBlocking {val id = noteRepository.insert(note)return@runBlocking Note(id, note.title, note.content)}fun insert(note: Note) = viewModelScope.launch {noteRepository.insert(note)}fun upate(note: Note) = viewModelScope.launch {noteRepository.update(note)}fun delete(note: Note) = viewModelScope.launch {noteRepository.delete(note)}
}class NoteViewModelFactory(private val noteRepository: NoteRepository) : ViewModelProvider.Factory {override fun <T : ViewModel> create(modelClass: Class<T>): T {if (modelClass.isAssignableFrom(NoteViewModel::class.java)) {return NoteViewModel(noteRepository) as T}throw IllegalArgumentException("Unknown ViewModel class")}
}

有了ViewModel,Activity就可以通过其访问数据库了。

可能大家会有疑问为什么需要ViewModel,Activity直接通过存储库来访问数据库不就可以了吗?
ViewModel的意义在于存储了界面数据,并且不受Activity的生命周期和配置更新所影响,这样就可以让Activity只关注绘制界面,而ViewModel只关注界面数据。如果没有ViewModel,Activity每次重启重新去读数据库就会浪费大量资源。

界面

有了ViewModel就可以构建我们的界面了,首先实现笔记本首页NotebookActivity,其可以展示目前所有的笔记,相当于是所有笔记的目录,我们对于每个笔记只显示其标题,并且还有添加笔记按钮,其实现如下:

class NotebookActivity : AppCompatActivity() {private val noteViewModel: NoteViewModel by viewModels { NoteViewModelFactory((application as NotebookApplication).noteRepository) }override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContent {MainContent(noteViewModel)}}companion object {fun actionStart(context: Context) {val intent = Intent(context, NotebookActivity::class.java)context.startActivity(intent)}}
}@Preview
@Composable
private fun PreviewContent() {RootContent(notes = listOf(Note(1, "11", "111"),Note(2, "22", "222"),Note(3, "33", "333"),), {Note(0, "", "")})
}@Composable
private fun MainContent(noteViewModel: NoteViewModel) {val notes by noteViewModel.allNotes.observeAsState(listOf())RootContent(notes, { noteViewModel.insertBlock(Note(0, "Title", "Content")) })
}@Composable
private fun RootContent(notes: List<Note>, onAddNote: () -> Note) {val context = LocalContext.currentScaffold(floatingActionButton = {Icon(Icons.Rounded.Add, "New note", Modifier.size(100.dp).clickable {val note = onAddNote()NoteActivity.actionStart(context, note)})}, content = {NoteList(notes = notes)})
}@Composable
private fun NoteList(notes: List<Note>) {val context = LocalContext.currentLazyColumn {items(notes) { note ->Text(text = note.title,Modifier.fillMaxWidth().padding(all = 30.dp).clickable { NoteActivity.actionStart(context, note) })}}
}

NotebookActivity可以跳转到笔记详情页NoteActivity,其实现如下:

class NoteActivity : AppCompatActivity() {private val noteViewModel: NoteViewModel by viewModels { NoteViewModelFactory((application as NotebookApplication).noteRepository) }override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)val note = intent.extras!!["note"] as NotesetContent {MainContent(note, noteViewModel)}}companion object {fun actionStart(context: Context, note: Note) {val intent = Intent(context, NoteActivity::class.java)intent.putExtra("note", note)context.startActivity(intent)}}
}@Preview
@Composable
private fun PreviewContent() {RootContent(note = Note(1, "title", "content"), {}, {})
}@Composable
private fun MainContent(note: Note, noteViewModel: NoteViewModel) {RootContent(note, { note -> noteViewModel.upate(note) }, { note -> noteViewModel.delete(note) })
}@Composable
private fun RootContent(note: Note, onNoteChange: (note: Note) -> Unit, deleteNote: (note: Note) -> Unit) {val activity = LocalContext.current as Activityvar openConfirmDeleteDialog by remember { mutableStateOf(false) }Column {var title by remember { mutableStateOf(note.title) }var content by remember { mutableStateOf(note.content) }Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {TextField(value = title, onValueChange = { title = it; onNoteChange(Note(note.id, title, content)) }, Modifier.weight(7f))Icon(Icons.Filled.Delete, "Delete note",Modifier.weight(1f).clickable { openConfirmDeleteDialog = true })}TextField(value = content, onValueChange = { content = it; onNoteChange(Note(note.id, title, content)) }, Modifier.fillMaxSize())}if (openConfirmDeleteDialog) {AlertDialog(onDismissRequest = { openConfirmDeleteDialog = false },title = { Text("Confirm delete note") },confirmButton = { Button(onClick = { openConfirmDeleteDialog = false; deleteNote(note); activity.finish() }) { Text("Delete") } },dismissButton = { Button(onClick = { openConfirmDeleteDialog = false }) { Text("Dismiss") } })}
}

每次笔记被编辑,其标题或内容文本发生变化后都去存入数据库,实现了笔记的实时保存,因此不需要再设计一个保存按钮了。

总结

完整源码地址:https://github.com/SSSxCCC/SCApp
Compose框架省去了编写xml,Room构建数据库省去了大量繁琐的SQL语句的编写,最终只用了少量代码实现了增删改功能的笔记本app。

安卓实现笔记本app相关推荐

  1. 如何root安卓手机_你的手机你做主!免 ROOT 卸载安卓手机预装APP

    蛮多安卓手机会在系统内预装一堆 "乱七八糟的" APP,一些APP大多用户都不会用到.这些预装的APP有些会长期在后台运行,不断的消耗你的运存.消耗电量,最难受的是这些预装APP, ...

  2. android icon命名规则,安卓手机的APP图标尺寸规范和图标命名规范

    安卓手机的APP图标尺寸规范和图标命名规范 点击查看原文 android图标包括:程序启动图标.底部菜单图标.弹出对话框顶部图标.长列表内部列表项图标.底部和底部tab标签图标. 1.安卓程序启动图标 ...

  3. 安卓简单天气预报app源码_七个个小众但实用的APP,效率翻倍~

    推荐7个小众但实用的APP 1.PDF处理助手 下面就是软件的启动图,没有任何广告.并且直接标明了这个软件的三大特点:简单.免费.快捷下面就是软件的启动图,没有任何广告.而且免注册登录即可使用,简直是 ...

  4. 连接真机开发安卓(Android)移动app MUI框架 完善购物车订单等页面——混合式开发(五)

    https://blog.csdn.net/hanhanwanghaha宝藏女孩 欢迎您的关注! 欢迎关注微信公众号:宝藏女孩的成长日记 如有转载,请注明出处(如不注明,盗者必究) 这周真的太忙了,就 ...

  5. android 图片转字符串,图片转字符文字怎么转?安卓字符图App

    原标题:图片转字符文字怎么转?安卓字符图App 很多朋友上网的时候都会看到字符图,所谓字符图,就是用文字来组成图片.那么字符图要怎么做呢?其实无论是PC还是手机,都有相应的制作工具.今天,笔者就来为大 ...

  6. android 登录界面开源代码_【程序源代码】一个安卓查询类app制作的开源项目

    " 关键字:工作流 框架 springboot" 正文:一个学习安卓查询类app制作的开源项目.可以用来联系查询类app的编写. 01 - android studio最近势头好猛 ...

  7. faststart可以卸载吗_你的手机你做主!免 ROOT 卸载安卓手机预装APP

    蛮多安卓手机会在系统内预装一堆 "乱七八糟的" APP,一些APP大多用户都不会用到.这些预装的APP有些会长期在后台运行,不断的消耗你的运存.消耗电量,最难受的是这些预装APP, ...

  8. 【APPInventor\腾讯云】使用APPInventor开发连接腾讯云的安卓物联网遥控APP

    [APPInventor\腾讯云]使用APPInventor开发连接腾讯云的安卓物联网遥控APP 背景 需求分析 功能分析 数据链路 操作逻辑 实现方式\工具 具体实现 结语 背景 课程作业需要,教师 ...

  9. 安卓手机远程控制app

    用一台安卓手机完全控制另外一台安卓手机,想一想是不是很酷炫,那么今天他来了 安卓手机远程控制app下载地址58588.goho.co

最新文章

  1. Vue底层实现原理概述
  2. 我觉得要技术者上升到整体去考虑会好点
  3. 1452.接水问题(思维)
  4. Eclipse debug neutron-server
  5. 【开源项目之路】jquery的build问题
  6. 使用 jQuery Mobile 与 HTML5 开发 Web App (七) —— jQuery Mobile 列表
  7. 使用 Boost 的 IPC 和 MPI 库进行并发编程
  8. Flutter的SnackBar
  9. delphi报列表索引越界怎么处理_深入了解散列表
  10. java 从_java-从查询字符串中过滤参数(使用番石榴?...
  11. 计算机网络驱动坏了怎么解决办法,网卡驱动异常怎么办_网卡驱动异常解决办法_飞翔教程...
  12. 如何把pdf转换成excel表格
  13. 财经365热点:当阿里巴巴不再讲“中台”
  14. vba 读取图片尺寸
  15. IP地址转换(c语言)
  16. mac 微信多开 应用程序多开
  17. JavaGUI编程 -- Swing之Icon、ImageIcon标签获取当前类同一级文件路径的资源
  18. 新加坡IT薪酬总结,
  19. 软件开发测试的5个部分
  20. 使用vector创建一个二维数组(一)

热门文章

  1. 武汉工程大计算机学校地址,武汉工程学院
  2. cesium 绘制轨迹
  3. 实数傅立叶变换和复数傅立叶变换
  4. Apache安装时出现OS:拒绝访问的解决办法
  5. 台湾--电话正则表达式
  6. java数组初始化0_Java自学-数组 初始化数组
  7. ExoPlayer播放器 开发者指南(官方权威指南译文)
  8. linux编译ipp多线程,Linux下Intel IPP编程环境的配置
  9. C++环境下部署深度学习模型方案
  10. 禅与摩托车维修艺术(2)