将对象添加到可变实时数据列表

问题描述

我正试图将两个商店添加到可变列表中,如下所示:

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
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...