您好,登錄后才能下訂單哦!
這篇文章主要講解了Android如何實現記事本功能,內容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
該記事本包含創建新條目,數據庫增刪改查,條目可編輯,滑動刪除與拖拽排序,簡單鬧鐘實現(還有個簡陋背景音樂開關就不提了太簡單),接下來逐一介紹一下。
build.gradle導入
apply plugin: 'kotlin-kapt' ''' implementation 'com.google.android.material:material:1.0.0' implementation 'de.hdodenhof:circleimageview:3.0.1' implementation 'com.android.support.constraint:constraint-layout:1.1.3' implementation 'androidx.room:room-runtime:2.1.0' implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0' implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0' implementation 'androidx.recyclerview:recyclerview:1.0.0' kapt "androidx.room:room-compiler:2.1.0"
沒什么多說的。
Room數據庫
room數據庫相比于sqlite來說對新人確實友好很多,在沒有SQL基礎的前提下,增刪改查等實現都很簡單,只需創建一個實例,便可在線程中進行。具體代碼為
①接口:
@Dao interface NoteDao { @Update fun updateNote(newNote: Note) @Query("select * from Note") fun loadAllNotes(): List<Note> @Query("select * from Note where title > :title") fun loadNotesLongerThan(title:String) : List<Note> @Query("select * from Note where id == :id") fun loadById(id:Long) :Note @Delete fun deleteNote(note: Note) @Query("delete from Note where title == :title") fun deleteNoteByTitle(title: String): Int @Insert fun insertNote(note: Note) }
②Appdatabase類(獲取實例
@Database(version = 1, entities = [Note::class]) abstract class AppDatabase: RoomDatabase(){ abstract fun noteDao() : NoteDao companion object{ //訪問實例 private var instance : AppDatabase? = null @Synchronized//同步化 fun getDatabase(context: Context):AppDatabase{ instance?.let { return it } return Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "app_database") .build().apply { instance = this } } } }
滑動刪除和拖拽排序
class RecycleItemTouchHelper(private val helperCallback: ItemTouchHelperCallback) : ItemTouchHelper.Callback() { //設置滑動類型標記 override fun getMovementFlags( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder ): Int { return makeMovementFlags(ItemTouchHelper.UP or ItemTouchHelper.DOWN, ItemTouchHelper.END or ItemTouchHelper.START ) } override fun isLongPressDragEnabled(): Boolean { return true } //滑動 override fun isItemViewSwipeEnabled(): Boolean { return true } //拖拽回調 override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { helperCallback.onMove(viewHolder.adapterPosition, target.adapterPosition) return true } //滑動 override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int): Unit { helperCallback.onItemDelete(viewHolder.adapterPosition) } //狀態回調 override fun onSelectedChanged( viewHolder: RecyclerView.ViewHolder?, actionState: Int ) { super.onSelectedChanged(viewHolder, actionState) } interface ItemTouchHelperCallback { fun onItemDelete(positon: Int) fun onMove(fromPosition: Int, toPosition: Int) } }
NoteAdapter接口實現
拖拽排序和滑動刪除后即更新一次,這種方法并不好,畢竟沒有用到MVVM中的高級組件,包括觀察者,Livedata,ViewModel察覺數據變化并提示更新。建議在這種方法的前提下可以考慮在從Activity離開后,再數據更新。
注:千萬不要在**onPause()**中涉及數據更新和保存!!!
//拖拽排序 override fun onMove(fromPosition: Int, toPosition: Int) { val noteDao = AppDatabase.getDatabase(context).noteDao() if (fromPosition < toPosition) { for (i in fromPosition until toPosition) { Collections.swap(noteList, i, i + 1) for (i in noteList){ Log.d("title", i.title) } Log.d("tag2", fromPosition.toString()+"->"+toPosition) } } else { for (i in fromPosition downTo toPosition + 1) { Collections.swap(noteList, i, i - 1) } } //排序后的數據更新 thread { var templist = noteDao.loadAllNotes().toMutableList() for (i in 0 until templist.size){ templist[i].title = noteList[i].title templist[i].content = noteList[i].content noteDao.updateNote(templist[i]) } } notifyItemMoved(fromPosition, toPosition) }
簡易鬧鐘實現
broadcast類需要自己實現
class MyReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { // This method is called when the BroadcastReceiver is receiving an Intent broadcast. Toast.makeText(context,"You have a task to do!!!", Toast.LENGTH_LONG).show() } }
這里只是發個廣播通知,并沒有提示聲音,可以采取發到通知欄的方式,系統會有提示音。涉及到AlarmManager類
NoteActivity中的實現:
setBtn.setOnClickListener { view -> val c = Calendar.getInstance() //調整為中國時區,不然有8小時差比較麻煩 val tz = TimeZone.getTimeZone("Asia/Shanghai") c.timeZone = tz //獲取當前時間 if (setHour.text.toString()!=""&&setMin.text.toString()!="") { c.set(Calendar.HOUR_OF_DAY, setHour.text.toString().toInt());//小時 c.set( Calendar.MINUTE, setMin.text.toString().toInt() );//分鐘 c.set(Calendar.SECOND, 0);//秒 } //計時發送通知 val mIntent = Intent(this, MyReceiver::class.java) val mPendingIntent = PendingIntent.getBroadcast(this, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT) am = this .getSystemService(Context.ALARM_SERVICE) as AlarmManager if (setHour.text.toString()==""||setMin.text.toString()==""|| setHour.text.toString().toInt() > 24 || setMin.text.toString().toInt() > 60) { Toast.makeText(this, "請輸入正確的時間格式!", Toast.LENGTH_SHORT).show() } else { Log.d("fuck10", c.timeInMillis.toString()) am!!.setExactAndAllowWhileIdle( AlarmManager.RTC_WAKEUP, c.timeInMillis, mPendingIntent ) Toast.makeText(this, "設置成功", Toast.LENGTH_SHORT).show() } }
其它方面如點擊recyclerView中的Item重新編輯時對原數據的展現,用到了setText(),這里注意不要跟kotlin中setText()和getText()搞混。
大概所有功能差不多就這些了,畢竟只是個記事本應用
看完上述內容,是不是對Android如何實現記事本功能有進一步的了解,如果還想學習更多內容,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。