所以我有一个简单的实现,在 a 中显示用户列表,并在asRecyclerView
中查询该列表。ViewModel
LiveData
问题是 UI 没有更新以显示最新列表 - 称为users
- 即使在观察列表时也是如此。我现在只是设置了一个演示用户列表。
这是我的视图模型:
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()
}
PS这UsersAdapter
是一个平常的RecyclerView.Adapter
。
我已经确保调用setValue
我的用户列表来调用观察者,因此我不确定这里缺少什么。我的适配器是否设置错误?