RecyclerView中的ViewModel

时间:2019-04-15 15:18:38

标签: android kotlin android-recyclerview viewmodel swiperefreshlayout

我正在使用ViewModel加载数据并将其设置为SwipeRefreshLayout RecyclerView

    mAdapter = NewRecyclerViewAdapter(listAct, this@MainActivity, hashMap)
    list?.adapter = mAdapter

     workViewModel.getRequests()?.observe(
                this, Observer { resource ->
                    resource?.data?.let {
                        Log.d(TAG,it.size)
                        mAdapter.setOrders(it)
                    }
                }
            )

  workViewModel = ViewModelProviders.of(
            this,
            ViewModelFactory.getInstance(activity.application)
        ).get(WorkViewModel::class.java)
                   .......


swipe_container.setOnRefreshListener {
            mAdapter.setWorkOrders(listAct)
            mAdapter.notifyDataSetChanged()
        }    

我使用日志进行调试,显示大小为2。数据似乎可以成功检索,但是未设置为recyclerView

适配器

 private var order = emptyList<Order>()
     ......
     internal fun setOrders(order: List<Order>) {
            this.order = order
            this.order.sortedBy { it.created_at }
            notifyDataSetChanged()
        }

2 个答案:

答案 0 :(得分:1)

您正在setOrders()函数中设置相同的列表 使用它代替函数

internal fun setOrders(orders: List<Order>) {
    this.order = orders.sortedBy { it.created_at }
    notifyDataSetChanged()
}

答案 1 :(得分:0)

您在任何地方都使用yourRecyclerView.setAdapter(mAdapter )吗?或者更好:您是否初始化了recyclerview并设置了适配器?如果您正在使用数据绑定,请在recyclerview xml标签中检查适配器属性