程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何在 Kotlin 列表的末尾将项目添加到存储库?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决如何在 Kotlin 列表的末尾将项目添加到存储库??

开发过程中遇到如何在 Kotlin 列表的末尾将项目添加到存储库?的问题如何解决?下面主要结合日常开发的经验,给出你关于如何在 Kotlin 列表的末尾将项目添加到存储库?的解决方法建议,希望对你解决如何在 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()
}

大佬总结

以上是大佬教程为你收集整理的如何在 Kotlin 列表的末尾将项目添加到存储库?全部内容,希望文章能够帮你解决如何在 Kotlin 列表的末尾将项目添加到存储库?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。