53 lines
1.6 KiB
Kotlin
53 lines
1.6 KiB
Kotlin
package com.example.myapplication
|
|
|
|
import android.os.Bundle
|
|
import android.widget.Button
|
|
import android.widget.EditText
|
|
import androidx.activity.ComponentActivity
|
|
import androidx.lifecycle.lifecycleScope
|
|
import androidx.recyclerview.widget.LinearLayoutManager
|
|
import androidx.recyclerview.widget.RecyclerView
|
|
import kotlinx.coroutines.launch
|
|
|
|
class MainActivity : ComponentActivity() {
|
|
|
|
private lateinit var etInput: EditText
|
|
private lateinit var btnAdd: Button
|
|
private lateinit var recyclerView: RecyclerView
|
|
private lateinit var adapter: NoteAdapter
|
|
|
|
private lateinit var db: AppDatabase
|
|
|
|
override fun onCreate(savedInstanceState: Bundle?) {
|
|
super.onCreate(savedInstanceState)
|
|
setContentView(R.layout.activity_main)
|
|
|
|
etInput = findViewById(R.id.etInput)
|
|
btnAdd = findViewById(R.id.btnAdd)
|
|
recyclerView = findViewById(R.id.recyclerView)
|
|
|
|
adapter = NoteAdapter(emptyList())
|
|
recyclerView.layoutManager = LinearLayoutManager(this)
|
|
recyclerView.adapter = adapter
|
|
|
|
db = AppDatabase.getDatabase(this)
|
|
|
|
// Добавляем заметку
|
|
btnAdd.setOnClickListener {
|
|
val text = etInput.text.toString()
|
|
if (text.isNotEmpty()) {
|
|
lifecycleScope.launch {
|
|
db.noteDao().insert(NoteEntity(text = text))
|
|
}
|
|
etInput.text.clear()
|
|
}
|
|
}
|
|
|
|
// Подписываемся на изменения
|
|
lifecycleScope.launch {
|
|
db.noteDao().getAll().collect { notes ->
|
|
adapter.update(notes)
|
|
}
|
|
}
|
|
}
|
|
} |