首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Android Jetpack:设置LiveData时RecyclerView没有更新

Android Jetpack:设置LiveData时RecyclerView没有更新
EN

Stack Overflow用户
提问于 2018-06-10 08:52:59
回答 1查看 4.1K关注 0票数 5

因此,我有一个简单的实现,可以在RecyclerView中显示用户列表,并在ViewModel中以LiveData的形式查询该列表。

问题是,即使观察到列表,UI也不会更新以显示最新的列表-称为users。我只是暂时建立了一个演示用户列表。

这是我的ViewModel:

代码语言:javascript
复制
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() }
    }
}

和我的ViewModel的附加片段:

代码语言:javascript
复制
// ...

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()
}

另外,UsersAdapter是一个普通的RecyclerView.Adapter

我已经确保调用我的用户列表上的setValue来调用观察者,因此我不确定这里缺少什么。我的适配器设置错误了吗?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50779740

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档