我想在自定义RecyclerView.Adapter中显示从ViewModel检索到的项目的新列表。为此,我将检索到的列表传递给适配器并调用notifyDataSetChanged()
,但是UI上没有任何变化。
我调试了代码,适配器的列表包含1个元素(UI显示1个元素),新检索到的列表具有2个元素-在适配器中设置新列表并调用notifyDataSetChanged()
UI不变后,但应附加该1个元素。
片段代码:
trip_details_participantsList.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
trip_details_participantsList.adapter = userBriefAdapter
tripsDetailsViewModel.getTripParticipants(tripId).observe(this, Observer {participants ->
tripsDetailsViewModel.getUsersBriefs(participants.map { x -> x.userId }).observe(this, Observer{ users ->
userBriefAdapter.setData(users)
})
})
自定义适配器和ViewHolder:
class UserBriefAdapter : RecyclerView.Adapter<UserBriefViewHolder>() {
private var users: List<UserBrief> = mutableListOf()
fun setData(items: List<UserBrief>){
this.users = items
notifyDataSetChanged()
}
override fun onBindViewHolder(holder: UserBriefViewHolder, position: Int) =
holder.bind(users[position])
override fun getItemCount() = users.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserBriefViewHolder {
val inflater = LayoutInflater.from(parent.context)
return UserBriefViewHolder(inflater, parent)
}
}
class UserBriefViewHolder(inflater: LayoutInflater, parent: ViewGroup) : RecyclerView.ViewHolder(inflater.inflate(
R.layout.trip_details_list_item, parent, false)) {
private var profilePictureImageView: ImageView = itemView.findViewById(R.id.trips_details_profile_image)
fun bind(userBrief: UserBrief){
Picasso.get()
.load(userBrief.profilePictureUrl)
.into(profilePictureImageView)
}
}
我已经阅读了有关它的现有主题,但是每个可接受的解决方案都类似于适配器的setData()
函数和notifyDataSetChanged()
。每当观察到的值更改时,我还尝试将UserBriefAdapter的新实例设置为RecyclerView,但是结果是相同的。当我来回浏览视图时,它可以正确显示元素,但是我想在不更改视图的情况下实现这一点。
这可能是线程问题。尝试在观察者回调中将可运行对象发布到主线程:
tripsDetailsViewModel.getUsersBriefs(participants.map { x -> x.userId }).observe(this, Observer{ users ->
view?.post { userBriefAdapter.setData(users) }
})
做了一些调试,发现不是notifyDataSetChanged()
。我向profilePictureUrl
传递了错误的UserBriefViewHolder
,因此Picasso库无法获取图像,因此未更新UI。