因此,我有一个简单的实现,可以在RecyclerView
中显示用户列表,并在ViewModel
中以LiveData
的形式查询该列表。
问题是,即使观察到列表,UI也不会更新以显示最新的列表-称为users
。我只是暂时建立了一个演示用户列表。
这是我的ViewModel:
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的附加片段:
// ...
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
来调用观察者,因此我不确定这里缺少什么。我的适配器设置错误了吗?
https://stackoverflow.com/questions/50779740
复制相似问题