如何解决AndroidJetpack中设置LiveData时RecyclerView 没有更新?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (601)

用户界面没有更新显示最新的列表,以下是我的视图模型:

class MainViewModel : ViewModel() {

    private val demoData = listOf(
            User(userName = "Bob", favoriteColor = "Green"),
            User(userName = "Jim", favoriteColor = "Red"),
            User(userName = "Park", favoriteColor = "Blue"),
            User(userName = "Tom", favoriteColor = "Yellow"),
            User(userName = "Lee", favoriteColor = "Black"),
            User(userName = "Xiu", favoriteColor = "Gray")
    )

    private val _users = MutableLiveData<List<User>>()
    val users: LiveData<List<User>>
        get() = _users

    init {
        _users.value = listOf()
    }

    fun loadUsers() {
        _users.value = demoData.toMutableList().apply { shuffle() }
    }
}

视图模型附带的片段:

// ...

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)

    viewModel.users.observe(this, Observer {
        mAdapter.notifyDataSetChanged()
    })

    mAdapter = UsersAdapter(viewModel.users.value!!)

    mainRV = view?.findViewById<RecyclerView>(R.id.rv_main)?.apply {
        adapter = mAdapter
        layoutManager = LinearLayoutManager(view?.context)
    }

    viewModel.loadUsers()
}

已经在我的用户列表中调用setValue在观察者,是适配器设置错误吗?

提问于
用户回答回答于

一收到数据,设置适配器:

viewModel.users.observe(this, Observer { items->
        mAdapter = UsersAdapter(items)
        mAdapter.notifyDataSetChanged()
    })

扫码关注云+社区

领取腾讯云代金券