根据集合中项目的数量,我想执行某些操作。
例如
if i have 1 item in collection -> doFirstAction()
if i have 2 or more items in collection -> doSecondAction()
if i have 2 or more items in collection and deleted all instead one -> doSecondAction()
在此基础上,我需要检查更改列表。
我发现了类似的内容:ObservableList。它似乎可以解决我的问题,但是不幸的是,我不知道如何正确使用它。
在我的课上,我需要检查以下集合:
var viewModels: List<ConnectionViewModel> = emptyList()
更新:
有了这个answer我写这样的东西:
var viewModels: ObservableList<ConnectionViewModel> = ObservableArrayList<ConnectionViewModel>()
并在我的收藏中添加侦听器:
fun setOnDataChange() {
viewModels.addOnListChangedCallback(object :
ObservableList.OnListChangedCallback<ObservableList<ConnectionViewModel>>() {
override fun onChanged(sender: ObservableList<ConnectionViewModel>?) {}
override fun onItemRangeRemoved(
sender: ObservableList<ConnectionViewModel>?,
positionStart: Int,
itemCount: Int
) {
showBiometricConfirmation = showConfirmation(itemCount)
}
override fun onItemRangeMoved(
sender: ObservableList<ConnectionViewModel>?,
fromPosition: Int,
toPosition: Int,
itemCount: Int
) {}
override fun onItemRangeInserted(
sender: ObservableList<ConnectionViewModel>?,
positionStart: Int,
itemCount: Int
) {
showBiometricConfirmation = showConfirmation(itemCount)
}
override fun onItemRangeChanged(
sender: ObservableList<ConnectionViewModel>?,
positionStart: Int,
itemCount: Int
) {}
})
}
private fun showConfirmation(itemCount: Int): Boolean {
return itemCount != 1
}
但是我有一些问题
我需要检查集合中的号码。如果数字是3,并且在删除2之后,我还需要调用
doSecondAction()
。但是如果集合号为1,则需要调用doFirstAction()
最佳答案
首先,您应该在android {}内部的gradle中启用dataBinding
android {
......
dataBinding {
enabled = true
}
}
然后,在您的代码中创建一个空列表:
val list: ObservableList<String> = ObservableArrayList<String>()
您可以这样设置监听器:
list.addOnListChangedCallback(object:ObservableList.OnListChangedCallback<ObservableList<String>>(){
override fun onChanged(sender: ObservableList<String>?) {
Log.d("Misha", "changed")
}
override fun onItemRangeRemoved(sender: ObservableList<String>?, positionStart: Int, itemCount: Int) {
...
}
override fun onItemRangeMoved(sender: ObservableList<String>?, fromPosition: Int, toPosition: Int, itemCount: Int) {
...
}
override fun onItemRangeInserted(sender: ObservableList<String>?, positionStart: Int, itemCount: Int) {
...
}
override fun onItemRangeChanged(sender: ObservableList<String>?, positionStart: Int, itemCount: Int) {
...
}
})
您可以像这样添加或删除值,或使用其他方法:
list.addAll(0, listOf("Misha", "Akopov"))