小编Pri*_*ani的帖子

当向RecyclerView ListAdapter提交新列表时,diff检查始终为areContentsTheSame()返回true。

我正在使用MVVM体系结构来构建简单的订购应用程序。我在我的ProductsFragment中使用RecyclerView列出了所有可以订购的产品。我还在ViewModel中使用LiveData,在Fragment中可以观察到它,以检查对产品列表的任何更改。

在我的列表项中,我有3个按钮:1个按钮,用于将产品添加到购物篮中,另一个按钮,用于增加客户想要添加到购物篮中的数量,第三个按钮用于减少客户想要添加到购物篮中的数量。

在我的产品数据类中,每当客户单击增量或减量按钮时,数量都会在数据模型中更新。

我还使用数据绑定将产品绑定到recyclerview列表项布局和Click侦听器。我正在使用ListAdapter开箱即用地访问DiffUtil。

我遇到的问题是,当通知了observable时,我想使用ListAdapter的SubmitList方法,以便在RecyclerView中仅更新已更改的项目。但是,我注意到DiffUtil方法areContentsTheSame()始终返回true。因此,列表项未更新。我不想使用notifyDatasetChanged,因为这会阻塞UI线程。

我遇到的另一个问题是,当我向购物篮中添加产品时,会保留对该产品的引用,因此当我向购物篮中添加产品时,当我只想更新MutableLiveData时,MutableLiveData也将更新。将产品添加到购物篮时,如何停止对正在创建的LiveData的引用?


产品浏览模型

class ProductsViewModel : ViewModel() {

    // LIVE DATA
    private val _basket = MutableLiveData<Basket>()

    val basket: LiveData<Basket>
        get() = _basket

    private val _products = MutableLiveData<List<Product>>()

    val products: LiveData<List<Product>>
        get() = _products


    init {
        _basket.value = Basket()
        _products.value = dummyData
    }

    fun onIncrementProductQuantityButtonPressed(product: Product) {
        //product.quantity += 1
        //val newList = _products.value

        //_products.value = newList   
        val newProduct = product.copy(quantity = product.quantity.plus(1))
        _basket.value!!.updateProductInBasket(newProduct)
        _basket.value = _basket.value
    }

    fun onDecrementProductQuantityButtonPressed(product: Product) {
        if (product.quantity>1) {
            //product.quantity = …
Run Code Online (Sandbox Code Playgroud)

android kotlin android-recyclerview android-mvvm android-livedata

2
推荐指数
1
解决办法
212
查看次数