用kotlin写一个安卓笔记app,支持安卓11,app启动后,具备添加新文件夹的功能,在一个文件夹内可以添加新笔记,编辑完笔记后可以点击保存,保存到数据库。对已经保存的笔记,可…
- User
用kotlin写一个安卓笔记app,支持安卓11,app启动后,具备添加新文件夹的功能,在一个文件夹内可以添加新笔记,编辑完笔记后可以点击保存,保存到数据库。对已经保存的笔记,可以在笔记列表中点击进行重新编辑 然后保存后更新笔记。支持删除已经保存的笔记的功能。此外还具备导出一键导出所有笔记保存为pdf的功能,导出到用户可以访问的Download文件夹中。支持搜索笔记的功能。支持在一个打开的笔记中搜索“关键词”的功能。在编辑笔记时,支持“撤销”操作。
- Assistant
创建一个功能完备的笔记应用涉及多个组件,包括数据库管理、用户界面设计、文件操作、搜索功能等。下面是一个使用 Kotlin 和 Android Jetpack(如 Room、ViewModel、LiveData)构建的基本框架示例,涵盖了您所需的主要功能。
由于篇幅限制,这里将给出关键代码示例和步骤指南,帮助您构建应用的各个部分。您可以根据这些示例扩展和完善应用。
项目结构概览
-
数据库层:
- 使用 Room 创建数据库,包括两个实体:Folder 和 Note。
-
UI层:
- 使用多个 Activity 和/或 Fragment 来管理不同的界面:
- MainActivity:显示文件夹列表,添加新文件夹。
- FolderActivity:显示特定文件夹内的笔记列表,添加、搜索、导出笔记。
- EditNoteActivity:编辑和保存笔记,支持撤销操作。
- 使用多个 Activity 和/或 Fragment 来管理不同的界面:
-
其他功能:
- PDF 导出功能。
- 搜索功能(全局和在笔记内)。
- 文件操作权限管理。
1. 设置 Room 数据库
1.1 添加依赖
在
build.gradle中添加 Room 相关依赖:dependencies { def room_version = "2.5.1" implementation "androidx.room:room-runtime:$room_version" kapt "androidx.room:room-compiler:$room_version" implementation "androidx.room:room-ktx:$room_version" // Lifecycle components implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.1" implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.6.1" // PDF implementation 'com.itextpdf:itext7-core:7.1.17' // For Undo feature implementation 'com.google.android.material:material:1.9.0' }1.2 定义实体
// Folder.kt import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "folders") data class Folder( @PrimaryKey(autoGenerate = true) val id: Long = 0, val name: String ) // Note.kt import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.ForeignKey @Entity( tableName = "notes", foreignKeys = [ForeignKey( entity = Folder::class, parentColumns = ["id"], childColumns = ["folderId"], onDelete = ForeignKey.CASCADE )] ) data class Note( @PrimaryKey(autoGenerate = true) val id: Long = 0, val folderId: Long, var title: String, var content: String, val timestamp: Long = System.currentTimeMillis() )1.3 定义 DAO
// FolderDao.kt import androidx.lifecycle.LiveData import androidx.room.* @Dao interface FolderDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(folder: Folder): Long @Delete suspend fun delete(folder: Folder) @Query("SELECT * FROM folders") fun getAllFolders(): LiveData<List<Folder>> } // NoteDao.kt import androidx.lifecycle.LiveData import androidx.room.* @Dao interface NoteDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(note: Note): Long @Update suspend fun update(note: Note) @Delete suspend fun delete(note: Note) @Query("SELECT * FROM notes WHERE folderId = :folderId ORDER BY timestamp DESC") fun getNotesByFolder(folderId: Long): LiveData<List<Note>> @Query("SELECT * FROM notes WHERE folderId = :folderId AND (title LIKE :query OR content LIKE :query) ORDER BY timestamp DESC") fun searchNotes(folderId: Long, query: String): LiveData<List<Note>> }1.4 定义数据库
// AppDatabase.kt import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import android.content.Context @Database(entities = [Folder::class, Note::class], version = 1, exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract fun folderDao(): FolderDao abstract fun noteDao(): NoteDao companion object { @Volatile private var instance: AppDatabase? = null fun getDatabase(context: Context): AppDatabase = instance ?: synchronized(this) { instance ?: Room.databaseBuilder( context.applicationContext, AppDatabase::class.java, "notes_db" ).build().also { instance = it } } } }2. 创建 Repository
// Repository.kt import androidx.lifecycle.LiveData class Repository(private val folderDao: FolderDao, private val noteDao: NoteDao) { fun getAllFolders(): LiveData<List<Folder>> = folderDao.getAllFolders() suspend fun insertFolder(folder: Folder): Long = folderDao.insert(folder) suspend fun deleteFolder(folder: Folder) = folderDao.delete(folder) fun getNotesByFolder(folderId: Long): LiveData<List<Note>> = noteDao.getNotesByFolder(folderId) fun searchNotes(folderId: Long, query: String): LiveData<List<Note>> = noteDao.searchNotes(folderId, "%$query%") suspend fun insertNote(note: Note): Long = noteDao.insert(note) suspend fun updateNote(note: Note) = noteDao.update(note) suspend fun deleteNote(note: Note) = noteDao.delete(note) }3. 创建 ViewModel
// MainViewModel.kt import androidx.lifecycle.* import kotlinx.coroutines.launch class MainViewModel(private val repository: Repository) : ViewModel() { val folders: LiveData<List<Folder>> = repository.getAllFolders() fun addFolder(name: String) = viewModelScope.launch { repository.insertFolder(Folder(name = name)) } fun deleteFolder(folder: Folder) = viewModelScope.launch { repository.deleteFolder(folder) } } // FolderViewModel.kt class FolderViewModel(private val repository: Repository, private val folderId: Long) : ViewModel() { val notes: LiveData<List<Note>> = repository.getNotesByFolder(folderId) private val _searchQuery = MutableLiveData<String>("") val filteredNotes: LiveData<List<Note>> = Transformations.switchMap(_searchQuery) { query -> if (query.isEmpty()) { repository.getNotesByFolder(folderId) } else { repository.searchNotes(folderId, query) } } fun setSearchQuery(query: String) { _searchQuery.value = query } fun addNote(title: String, content: String) = viewModelScope.launch { repository.insertNote(Note(folderId = folderId, title = title, content = content)) } fun deleteNote(note: Note) = viewModelScope.launch { repository.deleteNote(note) } } // EditNoteViewModel.kt class EditNoteViewModel(private val repository: Repository, private val noteId: Long?) : ViewModel() { // If noteId is null, it's a new note val note: LiveData<Note?> = noteId?.let { id -> repository.noteDao().getNoteById(id).asLiveData() } ?: MutableLiveData(null) fun saveNote(folderId: Long, title: String, content: String) = viewModelScope.launch { if (noteId == null) { repository.insertNote(Note(folderId = folderId, title = title, content = content)) } else { val currentNote = note.value if (currentNote != null) { currentNote.title = title currentNote.content = content repository.updateNote(currentNote) } } } }注意:您需要在
NoteDao中添加getNoteById方法:@Query("SELECT * FROM notes WHERE id = :id") fun getNoteById(id: Long): Flow<Note>4. 创建用户界面
4.1 MainActivity(显示文件夹列表)
布局 (
activity_main.xml):<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/btn_add_folder" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="添加文件夹" /> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler_folders" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> </LinearLayout>MainActivity.kt:
import android.content.Intent import android.os.Bundle import android.widget.Button import androidx.activity.viewModels import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { private val viewModel: MainViewModel by viewModels { MainViewModelFactory((application as MyApp).repository) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // 设置布局文件 setContentView(R.layout.activity_main) val recyclerView = findViewById<RecyclerView>(R.id.recycler_folders) val adapter = FolderListAdapter { folder -> // 点击文件夹,打开 FolderActivity val intent = Intent(this, FolderActivity::class.java).apply { putExtra("FOLDER_ID", folder.id) putExtra("FOLDER_NAME", folder.name) } startActivity(intent) } recyclerView.adapter = adapter recyclerView.layoutManager = LinearLayoutManager(this) viewModel.folders.observe(this) { folders -> folders?.let { adapter.submitList(it) } } val addFolderButton = findViewById<Button>(R.id.btn_add_folder) addFolderButton.setOnClickListener { showAddFolderDialog() } } private fun showAddFolderDialog() { val builder = AlertDialog.Builder(this) builder.setTitle("添加文件夹") val input = android.widget.EditText(this) input.hint = "文件夹名称" builder.setView(input) builder.setPositiveButton("确定") { dialog, _ -> val folderName = input.text.toString() if (folderName.isNotBlank()) { viewModel.addFolder(folderName) } dialog.dismiss() } builder.setNegativeButton("取消") { dialog, _ -> dialog.cancel() } builder.show() } }FolderListAdapter.kt:
import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter class FolderListAdapter(private val onClick: (Folder) -> Unit) : ListAdapter<Folder, FolderListAdapter.FolderViewHolder>(FolderDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FolderViewHolder { val view = LayoutInflater.from(parent.context) .inflate(android.R.layout.simple_list_item_1, parent, false) return FolderViewHolder(view, onClick) } override fun onBindViewHolder(holder: FolderViewHolder, position: Int) { holder.bind(getItem(position)) } class FolderViewHolder(itemView: View, val onClick: (Folder) -> Unit) : RecyclerView.ViewHolder(itemView) { private val textView: TextView = itemView.findViewById(android.R.id.text1) private var currentFolder: Folder? = null init { itemView.setOnClickListener { currentFolder?.let { onClick(it) } } } fun bind(folder: Folder) { currentFolder = folder textView.text = folder.name } } class FolderDiffCallback : DiffUtil.ItemCallback<Folder>() { override fun areItemsTheSame(oldItem: Folder, newItem: Folder): Boolean = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: Folder, newItem: Folder): Boolean = oldItem == newItem } }4.2 FolderActivity(显示笔记列表,添加、搜索、导出)
布局 (
activity_folder.xml):<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/search_notes" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:hint="搜索笔记" /> <Button android:id="@+id/btn_export_pdf" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="导出PDF" /> </LinearLayout> <Button android:id="@+id/btn_add_note" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="添加笔记" /> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler_notes" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> </LinearLayout>FolderActivity.kt:
import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import kotlinx.coroutines.* class FolderActivity : AppCompatActivity() { private lateinit var folderName: String private var folderId: Long = -1L private val viewModel: FolderViewModel by viewModels { FolderViewModelFactory((application as MyApp).repository, folderId) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // 设置布局文件 setContentView(R.layout.activity_folder) folderId = intent.getLongExtra("FOLDER_ID", -1L) folderName = intent.getStringExtra("FOLDER_NAME") ?: "未知文件夹" setTitle(folderName) val recyclerView = findViewById<RecyclerView>(R.id.recycler_notes) val adapter = NoteListAdapter( onEdit = { note -> // 打开 EditNoteActivity 进行编辑 val intent = Intent(this, EditNoteActivity::class.java).apply { putExtra("NOTE_ID", note.id) putExtra("FOLDER_ID", folderId) } startActivity(intent) }, onDelete = { note -> // 删除笔记 viewModel.deleteNote(note) Toast.makeText(this, "已删除笔记", Toast.LENGTH_SHORT).show() } ) recyclerView.adapter = adapter recyclerView.layoutManager = LinearLayoutManager(this) viewModel.filteredNotes.observe(this) { notes -> notes?.let { adapter.submitList(it) } } val addNoteButton = findViewById<Button>(R.id.btn_add_note) addNoteButton.setOnClickListener { // 打开 EditNoteActivity 添加新笔记 val intent = Intent(this, EditNoteActivity::class.java).apply { putExtra("FOLDER_ID", folderId) } startActivity(intent) } val searchEditText = findViewById<EditText>(R.id.search_notes) searchEditText.addTextChangedListener(object : android.text.TextWatcher { override fun afterTextChanged(s: android.text.Editable?) { viewModel.setSearchQuery(s.toString()) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} }) val exportButton = findViewById<Button>(R.id.btn_export_pdf) exportButton.setOnClickListener { exportNotesToPDF() } } private fun exportNotesToPDF() { // 请求权限 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) { // Android 10及以上不需要外部存储权限 performExport() } else { // 处理低版本权限 // 这里简化处理,请根据需要添加权限请求逻辑 performExport() } } private fun performExport() { viewModel.filteredNotes.value?.let { notes -> GlobalScope.launch(Dispatchers.IO) { try { val pdfDocument = com.itextpdf.layout.Document(com.itextpdf.kernel.pdf.PdfWriter( getExternalFilesDir(null)?.absolutePath + "/notes.pdf" )) val pdf = com.itextpdf.layout.Document(pdfDocument) for (note in notes) { pdf.add(com.itextpdf.layout.element.Paragraph("标题: ${note.title}")) pdf.add(com.itextpdf.layout.element.Paragraph("内容: ${note.content}")) pdf.add(com.itextpdf.layout.element.Paragraph("时间: ${java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(java.util.Date(note.timestamp))}")) pdf.add(com.itextpdf.layout.element.LineSeparator()) } pdf.close() withContext(Dispatchers.Main) { Toast.makeText(this@FolderActivity, "导出成功", Toast.LENGTH_SHORT).show() } } catch (e: Exception) { e.printStackTrace() withContext(Dispatchers.Main) { Toast.makeText(this@FolderActivity, "导出失败", Toast.LENGTH_SHORT).show() } } } } } }NoteListAdapter.kt:
import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter class NoteListAdapter( private val onEdit: (Note) -> Unit, private val onDelete: (Note) -> Unit ) : ListAdapter<Note, NoteListAdapter.NoteViewHolder>(NoteDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteViewHolder { val view = LayoutInflater.from(parent.context) .inflate(android.R.layout.simple_list_item_2, parent, false) return NoteViewHolder(view, onEdit, onDelete) } override fun onBindViewHolder(holder: NoteViewHolder, position: Int) { holder.bind(getItem(position)) } class NoteViewHolder( itemView: View, val onEdit: (Note) -> Unit, val onDelete: (Note) -> Unit ) : RecyclerView.ViewHolder(itemView) { private val titleView: TextView = itemView.findViewById(android.R.id.text1) private val contentView: TextView = itemView.findViewById(android.R.id.text2) private val deleteButton: ImageButton private var currentNote: Note? = null init { deleteButton = ImageButton(itemView.context).apply { setImageResource(android.R.drawable.ic_delete) layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) setOnClickListener { currentNote?.let { onDelete(it) } } } if (itemView is ViewGroup) { itemView.addView(deleteButton) } itemView.setOnClickListener { currentNote?.let { onEdit(it) } } } fun bind(note: Note) { currentNote = note titleView.text = note.title contentView.text = note.content.take(100) // 简略显示内容 } } class NoteDiffCallback : DiffUtil.ItemCallback<Note>() { override fun areItemsTheSame(oldItem: Note, newItem: Note): Boolean = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: Note, newItem: Note): Boolean = oldItem == newItem } }4.3 EditNoteActivity(编辑笔记,支持撤销)
布局 (
activity_edit_note.xml):<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="16dp" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/edit_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="标题" /> <EditText android:id="@+id/edit_content" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:hint="内容" android:gravity="top" android:inputType="textMultiLine" /> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/btn_save_note" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="保存" /> <Button android:id="@+id/btn_undo" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="撤销" /> </LinearLayout> </LinearLayout>EditNoteActivity.kt:
import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity class EditNoteActivity : AppCompatActivity() { private var noteId: Long? = null private var folderId: Long = -1L private lateinit var titleEditText: EditText private lateinit var contentEditText: EditText private lateinit var saveButton: Button private lateinit var undoButton: Button private val viewModel: EditNoteViewModel by viewModels { EditNoteViewModelFactory( (application as MyApp).repository, noteId ) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // 设置布局文件 setContentView(R.layout.activity_edit_note) noteId = intent.getLongExtra("NOTE_ID", -1L).let { if (it == -1L) null else it } folderId = intent.getLongExtra("FOLDER_ID", -1L) titleEditText = findViewById(R.id.edit_title) contentEditText = findViewById(R.id.edit_content) saveButton = findViewById(R.id.btn_save_note) undoButton = findViewById(R.id.btn_undo) viewModel.note.observe(this) { note -> if (note != null) { titleEditText.setText(note.title) contentEditText.setText(note.content) } } saveButton.setOnClickListener { val title = titleEditText.text.toString() val content = contentEditText.text.toString() if (folderId != -1L) { viewModel.saveNote(folderId, title, content) Toast.makeText(this, "已保存", Toast.LENGTH_SHORT).show() finish() } else { Toast.makeText(this, "文件夹ID错误", Toast.LENGTH_SHORT).show() } } // 实现撤销功能 undoButton.setOnClickListener { handleUndo() } } private fun handleUndo() { // 简单撤销逻辑:清空文本 contentEditText.text.clear() Toast.makeText(this, "已撤销", Toast.LENGTH_SHORT).show() } }注意:这里的撤销功能非常简单,仅作为示例。更复杂的撤销操作可以使用
UndoManager或维护文本变化历史。5. 权限管理和文件导出
在 Android 11 (API 级别 30) 上,存储权限有所变化。为了将 PDF 导出到
Download文件夹,可以使用以下方法:使用 MediaStore API 导出 PDF:
private fun performExport() { viewModel.filteredNotes.value?.let { notes -> GlobalScope.launch(Dispatchers.IO) { try { val pdfFileName = "Notes_${System.currentTimeMillis()}.pdf" val resolver = contentResolver val contentValues = android.content.ContentValues().apply { put(android.provider.MediaStore.MediaColumns.DISPLAY_NAME, pdfFileName) put(android.provider.MediaStore.MediaColumns.MIME_TYPE, "application/pdf") if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) { put(android.provider.MediaStore.MediaColumns.RELATIVE_PATH, android.os.Environment.DIRECTORY_DOWNLOADS) } else { val downloadDir = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).absolutePath put(android.provider.MediaStore.MediaColumns.DATA, "$downloadDir/$pdfFileName") } } val uri = resolver.insert(android.provider.MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues) uri?.let { val outputStream = resolver.openOutputStream(it) val pdfDocument = com.itextpdf.layout.Document(com.itextpdf.kernel.pdf.PdfWriter(outputStream)) for (note in notes) { pdfDocument.add(com.itextpdf.layout.element.Paragraph("标题: ${note.title}")) pdfDocument.add(com.itextpdf.layout.element.Paragraph("内容: ${note.content}")) pdfDocument.add(com.itextpdf.layout.element.Paragraph("时间: ${java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(java.util.Date(note.timestamp))}")) pdfDocument.add(com.itextpdf.layout.element.LineSeparator()) } pdfDocument.close() withContext(Dispatchers.Main) { Toast.makeText(this@FolderActivity, "导出成功到 Download 文件夹", Toast.LENGTH_SHORT).show() } } ?: throw Exception("Failed to create PDF file") } catch (e: Exception) { e.printStackTrace() withContext(Dispatchers.Main) { Toast.makeText(this@FolderActivity, "导出失败", Toast.LENGTH_SHORT).show() } } } } }注意: 请确保在
AndroidManifest.xml中声明必要的权限:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" />对于 Android 10 及以上版本,建议使用
MediaStoreAPI,无需请求存储权限。6. 搜索笔记内关键词
在
EditNoteActivity,添加一个搜索框来搜索内容关键词。修改布局 (
activity_edit_note.xml):<!-- 在 contentEditText 下面添加一个搜索框 --> <EditText android:id="@+id/search_keyword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="搜索关键词" /> <TextView android:id="@+id/search_result" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="" />修改
EditNoteActivity.kt:// 在 onCreate 中添加 val searchKeywordEditText = findViewById<EditText>(R.id.search_keyword) val searchResultTextView = findViewById<TextView>(R.id.search_result) searchKeywordEditText.addTextChangedListener(object : android.text.TextWatcher { override fun afterTextChanged(s: android.text.Editable?) { val keyword = s.toString() if (keyword.isNotEmpty()) { val content = contentEditText.text.toString() val index = content.indexOf(keyword, ignoreCase = true) if (index != -1) { searchResultTextView.text = "找到关键词位于位置: $index" } else { searchResultTextView.text = "未找到关键词" } } else { searchResultTextView.text = "" } } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} })解释: 这个简单的搜索功能会在用户输入关键词时,搜索关键词在笔记内容中的位置,并显示结果。
7. 创建 Application 类
为了方便在 ViewModel 中使用 Repository,可以创建一个自定义的
Application类。// MyApp.kt import android.app.Application class MyApp : Application() { val database by lazy { AppDatabase.getDatabase(this) } val repository by lazy { Repository(database.folderDao(), database.noteDao()) } }并在
AndroidManifest.xml中声明:<application android:name=".MyApp" ... > ... </application>8. 创建 ViewModel Factory
为了向 ViewModel 传递参数(例如 FolderId 和 NoteId),需要创建相应的工厂。
// MainViewModelFactory.kt import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider class MainViewModelFactory(private val repository: Repository) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(MainViewModel::class.java)){ @Suppress("UNCHECKED_CAST") return MainViewModel(repository) as T } throw IllegalArgumentException("Unknown ViewModel class") } } // FolderViewModelFactory.kt class FolderViewModelFactory(private val repository: Repository, private val folderId: Long) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(FolderViewModel::class.java)){ @Suppress("UNCHECKED_CAST") return FolderViewModel(repository, folderId) as T } throw IllegalArgumentException("Unknown ViewModel class") } } // EditNoteViewModelFactory.kt class EditNoteViewModelFactory(private val repository: Repository, private val noteId: Long?) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(EditNoteViewModel::class.java)){ @Suppress("UNCHECKED_CAST") return EditNoteViewModel(repository, noteId) as T } throw IllegalArgumentException("Unknown ViewModel class") } }总结
以上代码示例提供了一个基本的框架,涵盖了文件夹和笔记的添加、编辑、删除,笔记的搜索以及导出为 PDF 的功能。由于应用的复杂性和篇幅限制,某些部分(如详细的错误处理、更完善的 UI 优化、复杂的撤销功能等)尚未完全展开。您可以根据这些示例进行扩展和优化,以满足具体需求。
进一步优化建议
- UI优化:使用更现代的 UI 组件,如 RecyclerView 的高级用法,布局优化等。
- 撤销功能:实现更复杂的撤销功能,例如使用
UndoManager或保存文本变化历史。 - 权限管理:完善用户权限请求逻辑,确保应用在各种 Android 版本上的兼容性。
- PDF格式美化:使用 iText 或其他库来美化导出的 PDF,添加样式、目录等。
- 错误处理和用户反馈:增加更详细的错误处理和用户操作反馈,提升体验。
希望这些示例和指南能帮助您构建所需的安卓笔记应用!
-