我正在使用新的支持库ListAdapter
。这是我的适配器代码
class ArtistsAdapter : ListAdapter<Artist, ArtistsAdapter.ViewHolder>(ArtistsDiff()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(parent.inflate(R.layout.item_artist))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position))
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bind(artist: Artist) {
itemView.artistDetails.text = artist.artistAlbums
.plus(" Albums")
.plus(" \u2022 ")
.plus(artist.artistTracks)
.plus(" Tracks")
itemView.artistName.text = artist.artistCover
itemView.artistCoverImage.loadURL(artist.artistCover)
}
}
}
我正在使用更新适配器
musicViewModel.getAllArtists().observe(this, Observer {
it?.let {
artistAdapter.submitList(it)
}
})
我的差异课
class ArtistsDiff : DiffUtil.ItemCallback<Artist>() {
override fun areItemsTheSame(oldItem: Artist?, newItem: Artist?): Boolean {
return oldItem?.artistId == newItem?.artistId
}
override fun areContentsTheSame(oldItem: Artist?, newItem: Artist?): Boolean {
return oldItem == newItem
}
}
发生的情况是,适配器首次呈现所有项目时调用了commitList,但是使用更新的对象属性再次调用SubmitList时,它不会重新呈现已更改的视图。
当我滚动列表时,它会重新渲染视图,依次调用 bindView()
另外,我注意到adapter.notifyDatasSetChanged()
在提交列表之后调用会以更新的值呈现视图,但是我不想调用,notifyDataSetChanged()
因为列表适配器内置了diff utils
有人能帮我一下吗?
编辑:我明白为什么发生这种情况不是我的意思。我的观点是,它至少需要发出警告或调用该notifyDataSetChanged()
函数。因为显然我调用该submitList(...)
函数是有原因的。我敢肯定,人们一直在努力找出问题出在几个小时之内,直到他们弄清楚submitList()忽略了该调用。
这是因为有Google
奇怪的逻辑。因此,如果将相同的列表传递给适配器,它甚至不会调用DiffUtil
。
public void submitList(final List<T> newList) {
if (newList == mList) {
// nothing to do
return;
}
....
}
ListAdapter
如果它不能处理同一列表中的更改,我真的不理解这一切。如果要更改列表中的项目,请传递给ListAdapter
和查看更改,然后您需要创建列表的深层副本,或者需要对RecyclerView
自己的DiffUtill
类使用常规。
因为它需要先前的状态才能执行差异。当然,如果您覆盖以前的状态,它将无法处理。O_o
是的,但那时候,我有一个理由叫
submitList
,对吗?它至少应该调用,notifyDataSetChanged()
而不是无声地忽略该调用。我敢肯定,人们一直在努力找出问题出在几个小时之前,直到他们submitList()
默默地忽略了呼叫。所以我回
RecyclerView.Adapter<VH>
并notifyDataSetChanged()
。生活现在很好。浪费好几个小时