问题描述
我正试图将两个商店添加到可变列表中,如下所示:
private var _shopList = MutableLiveData<List<Shop>>()
var shopList: LiveData<List<Shop>> = ()
get() = _shopList
// This function will get the arrayList items
fun getArrayList(): MutableLiveData<List<Shop>>
{
// Here we need to get the data
val shop1 = Shop("AOB","Lat and Long","LA")
val shop2 = Shop("Peach","Vegas")
_shopList.add(shop1)
_shopList.add(shop2)
return _shopList
}
但是它说没有引用添加功能?
解决方法
来自文档:
List:元素的一般有序集合。此接口中的方法仅支持对列表的只读访问;请参见通过MutableList接口支持读/写访问。
MutableList:元素的一般有序集合,支持添加和删除元素。
您可以修改MutableList:更改,删除,添加...其元素。在列表中,您只能阅读它们。
解决方案-
private var _shopList = MutableLiveData<List<Shop>>() // List is fine here as read only
val shopList: LiveData<List<Shop>> // List is fine here as read only
get() = _shopList
// This function will get the arrayList items
fun getArrayList(): MutableLiveData<List<Shop>> {
// Here we need to get the data
val shop1 = Shop("AOB","Lat and Long","LA") // var to val
val shop2 = Shop("Peach","Vegas") //var to val
_shopList.value = mutableListOf(shop1,shop2) // assigns a mutable list as value to the live data which can be observed in the view
return _shopList
}
,
这是解决方案:
private var _shopList = MutableLiveData<MutableList<Shop>>()
val shopList: LiveData<MutableList<Shop>>
get() = _shopList
// This function will get the arrayList items
fun getArrayList(): MutableLiveData<MutableList<Shop>>
{
// Here we need to get the data
var shop1 = Shop("AOB","LA")
var shop2 = Shop("Peach","Vegas")
_shopList.value = mutableListOf(shop1,shop2)
return _shopList
}