如何解决如何在 Kotlin 列表的末尾将项目添加到存储库?
我有几个 EditText 字段:标题、描述、日期。此外,还有一个保存按钮。通过单击它,应验证这些字段是否为空,如果一切正确,则会显示已添加项目的吐司,添加屏幕(NewItemActivity)将关闭,并应添加新项目到列表末尾的存储库。我检查了空字段。告诉我如何通过调用 toast 并关闭屏幕将项目添加到列表末尾的存储库中?我认为需要完成 ViewModel,但我不确定。如果你能给出一个详细描述的例子,那就太好了。
解决方法
要关闭任何 target: server
,请调用其 Activity
方法。例如,如果您想通过点击 finish()
来关闭 NewItemActivity
,
saveButton
并在列表末尾添加一个项目:
替换 saveButton.setOnClickListener {
Toast.makeText(this,"Closing newActivity",Toast.LENGTH_SHORT).show()
updateMechanism() // whatever you want to do...
finish()
}
List
带有interface MyItemsRepository {
val items: List<ItemModel>
ArrayList
,
非常简单,只需在您的界面中创建一个新方法即可:
interface MyItemsRepository {
val items: ArrayList<ItemModel> // change to this from List<ItemModel>
....
fun saveNewItem(item: ItemModel)
}
然后在您的存储库实现中实现相同的:
class MyItemsRepositoryImpl private constructor() : MyItemsRepository {
....
override fun saveNewItem(item: ItemModel) {
items.add(item)
}
}
从 ViewModel 调用此方法:
class ContentViewModel(
private val repository: MyItemsRepository
) : ViewModel() {
....
fun saveNewItem(item: ItemModel) = repository.saveNewItem(item: ItemModel)
}
现在从保存按钮的 OnClickListener 调用此方法。就是这样。
saveButton.setOnClickListener {
....
val newItem = ItemModel(/*add data from editext here*/)
viewModel.saveNewItem(newItem)
// You don't have to wait for the result of your insertion operation since you're just adding it into a list. If you were to use the database,then you might need to wait for the insertion and then finish the activity.
Toast.makeText(this,"New item added successfully",Toast.LENGTH_SHORT).show()
activity.finish()
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。