如果只是项目的内容发生变化,PagedListAdapter 不会更新列表
PagedListAdapter does not update list if just the content of an item changes
我正在使用 Room 和 Paging 库来显示类别。
我的实体:
@Entity(tableName = Database.Table.CATEGORIES)
data class Category(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = ID) var id: Long = 0,
@ColumnInfo(name = NAME) var name: String = "",
@ColumnInfo(name = ICON_ID) var iconId: Int = 0,
@ColumnInfo(name = COLOR) @ColorInt var color: Int = DEFAULT_COLOR
)
我的 DAO:
@Query("SELECT * FROM $CATEGORIES")
fun getPagedCategories(): DataSource.Factory<Int, Category>
@Update
fun update(category: Category)
我的回购:
val pagedCategoriesList: LiveData<PagedList<Category>> = categoryDao.getPagedCategories().toLiveData(Config(CATEGORIES_LIST_PAGE_SIZE))
我的视图模型:
val pagedCategoriesList: LiveData<PagedList<Category>>
get() = repository.pagedCategoriesList
我的适配器:
class CategoriesAdapter(val context: Context) : PagedListAdapter<Category, CategoriesAdapter.CategoryViewHolder>(CategoriesDiffCallback()) {
//region Adapter
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryViewHolder {
return CategoryViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_category, parent, false))
}
override fun onBindViewHolder(holder: CategoryViewHolder, position: Int) {
holder.bind(getItem(position)!!)
}
//endregion
//region Methods
fun getItemAt(position: Int): Category = getItem(position)!!
//endregion
inner class CategoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val iconHelper = IconHelper.getInstance(context)
fun bind(category: Category) {
with(itemView) {
txvCategoryItemText.text = category.name
imvCategoryItemIcon.setBackgroundColor(category.color)
iconHelper.addLoadCallback {
imvCategoryItemIcon.setImageDrawable(iconHelper.getIcon(category.iconId).getDrawable(context))
}
}
}
}
class CategoriesDiffCallback : DiffUtil.ItemCallback<Category>() {
override fun areItemsTheSame(oldItem: Category, newItem: Category): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Category, newItem: Category): Boolean {
return oldItem == newItem
}
}
}
还有我的片段:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
categoryViewModel = ViewModelProviders.of(this).get(CategoryViewModel::class.java)
adapter = CategoriesAdapter(requireContext())
categoryViewModel.pagedCategoriesList.observe(this, Observer(adapter::submitList))
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
ViewCompat.setTooltipText(fabNewCategory, getString(R.string.NewCategory))
with(mRecyclerView) {
layoutManager = GridLayoutManager(requireContext(), 4)
itemAnimator = DefaultItemAnimator()
addItemDecoration(SpacesItemDecoration(resources.getDimensionPixelSize(R.dimen.card_default_spacing)))
addOnItemTouchListener(OnItemTouchListener(requireContext(), this, this@CategoriesFragment))
}
mRecyclerView.adapter = adapter
fabNewCategory.setOnClickListener(this)
}
插入、删除或仅加载类别时一切正常。
但是当我更新单个实体的颜色或文本时,列表没有更新,尽管提交列表被正确调用。
调试了整个过程,发现问题:
提交列表后,调用 AsyncPagedListDiffer#submitList
。我比较了之前的列表(AsyncPagedListDiffer
中的mPagedList
)和新列表(AsyncPagedListDiffer#submitList
中的pagedList
)。我在那里编辑的项目是相等的,并且已经保存了新数据。因此 DiffUtil
比较所有内容,虽然显示的列表未更新,但项目已经相等。
如果该列表是一个参考,它可以解释为什么数据已经在适配器列表中刷新,但是我该如何解决这个问题?
除非您展示您的 Dao 和包含 DiffUtill.itemcallaback 的 pagedlistadapter class,否则没有人能够回答您的问题。
我给你看一些可能有用的代码。
你必须像这样在你的 DAO 接口中实现更新:
@更新
有趣的更新用户(数据:MyData)
如果你之后有这个方法,你检查你的 diffcall 如下:
companion object {
val videosDiffCallback = object : DiffUtil.ItemCallback<Item>(){
override fun areItemsTheSame(oldItem: Item, newItem: Item): Boolean {
return oldItem.id == newItem.id //Called to decide whether two objects(new and old items) represent the same item.
}
override fun areContentsTheSame(oldItem: Item, newItem: Item): Boolean {
return oldItem == newItem //Called to decide whether two items have the same data.
}
}
}
//oldItem Value: The item in the old list.
//newItem Value: The item in the new list.
我认为问题不在于您加载新数据的方式,而在于更新数据。虽然您没有向我们展示您触发项目更新的部分或实际更新是如何发生的,但我猜,如果我错了,抱歉,您可能会像这样直接编辑列表元素:
category = adapter.getItemAt(/*item position*/)
category.name = "a new name"
category.color = 5
categoryViewModel.update(category)
相反,您应该创建一个新的 Category
对象而不是修改现有对象,如下所示:
prevCategory = adapter.getItemAt(/*put position*/) // Do not edit prevCategory!
newCategory = Category(id=prevCategory.id, name="a new name", color=5, iconId=0)
categoryViewModel.update(newCategory)
每次您想进行哪怕是最小的更改时都创建一个全新的新对象的想法一开始可能并不那么明显,但是这种反应式实现依赖于每个事件都独立于其他事件的假设。使您的数据 class 不可变,或实际上不可变将防止此问题。
为了避免这种错误,我喜欢做的是,我总是将数据中的每个字段class设为最终字段。
@Entity(tableName = Database.Table.CATEGORIES)
data class Category(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = ID) val id: Long = 0,
@ColumnInfo(name = NAME) val name: String = "",
@ColumnInfo(name = ICON_ID) val iconId: Int = 0,
@ColumnInfo(name = COLOR) @ColorInt val color: Int = DEFAULT_COLOR
)
我已经在 PagedListAdapter 上进行了 RnD,并使用 Room 数据库进行了自定义分页。
单击here,您将找到我的实现。希望对您有所帮助。
谢谢。
我正在使用 Room 和 Paging 库来显示类别。
我的实体:
@Entity(tableName = Database.Table.CATEGORIES)
data class Category(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = ID) var id: Long = 0,
@ColumnInfo(name = NAME) var name: String = "",
@ColumnInfo(name = ICON_ID) var iconId: Int = 0,
@ColumnInfo(name = COLOR) @ColorInt var color: Int = DEFAULT_COLOR
)
我的 DAO:
@Query("SELECT * FROM $CATEGORIES")
fun getPagedCategories(): DataSource.Factory<Int, Category>
@Update
fun update(category: Category)
我的回购:
val pagedCategoriesList: LiveData<PagedList<Category>> = categoryDao.getPagedCategories().toLiveData(Config(CATEGORIES_LIST_PAGE_SIZE))
我的视图模型:
val pagedCategoriesList: LiveData<PagedList<Category>>
get() = repository.pagedCategoriesList
我的适配器:
class CategoriesAdapter(val context: Context) : PagedListAdapter<Category, CategoriesAdapter.CategoryViewHolder>(CategoriesDiffCallback()) {
//region Adapter
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryViewHolder {
return CategoryViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_category, parent, false))
}
override fun onBindViewHolder(holder: CategoryViewHolder, position: Int) {
holder.bind(getItem(position)!!)
}
//endregion
//region Methods
fun getItemAt(position: Int): Category = getItem(position)!!
//endregion
inner class CategoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val iconHelper = IconHelper.getInstance(context)
fun bind(category: Category) {
with(itemView) {
txvCategoryItemText.text = category.name
imvCategoryItemIcon.setBackgroundColor(category.color)
iconHelper.addLoadCallback {
imvCategoryItemIcon.setImageDrawable(iconHelper.getIcon(category.iconId).getDrawable(context))
}
}
}
}
class CategoriesDiffCallback : DiffUtil.ItemCallback<Category>() {
override fun areItemsTheSame(oldItem: Category, newItem: Category): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Category, newItem: Category): Boolean {
return oldItem == newItem
}
}
}
还有我的片段:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
categoryViewModel = ViewModelProviders.of(this).get(CategoryViewModel::class.java)
adapter = CategoriesAdapter(requireContext())
categoryViewModel.pagedCategoriesList.observe(this, Observer(adapter::submitList))
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
ViewCompat.setTooltipText(fabNewCategory, getString(R.string.NewCategory))
with(mRecyclerView) {
layoutManager = GridLayoutManager(requireContext(), 4)
itemAnimator = DefaultItemAnimator()
addItemDecoration(SpacesItemDecoration(resources.getDimensionPixelSize(R.dimen.card_default_spacing)))
addOnItemTouchListener(OnItemTouchListener(requireContext(), this, this@CategoriesFragment))
}
mRecyclerView.adapter = adapter
fabNewCategory.setOnClickListener(this)
}
插入、删除或仅加载类别时一切正常。 但是当我更新单个实体的颜色或文本时,列表没有更新,尽管提交列表被正确调用。
调试了整个过程,发现问题:
提交列表后,调用 AsyncPagedListDiffer#submitList
。我比较了之前的列表(AsyncPagedListDiffer
中的mPagedList
)和新列表(AsyncPagedListDiffer#submitList
中的pagedList
)。我在那里编辑的项目是相等的,并且已经保存了新数据。因此 DiffUtil
比较所有内容,虽然显示的列表未更新,但项目已经相等。
如果该列表是一个参考,它可以解释为什么数据已经在适配器列表中刷新,但是我该如何解决这个问题?
除非您展示您的 Dao 和包含 DiffUtill.itemcallaback 的 pagedlistadapter class,否则没有人能够回答您的问题。 我给你看一些可能有用的代码。
你必须像这样在你的 DAO 接口中实现更新:
@更新 有趣的更新用户(数据:MyData)
如果你之后有这个方法,你检查你的 diffcall 如下:
companion object {
val videosDiffCallback = object : DiffUtil.ItemCallback<Item>(){
override fun areItemsTheSame(oldItem: Item, newItem: Item): Boolean {
return oldItem.id == newItem.id //Called to decide whether two objects(new and old items) represent the same item.
}
override fun areContentsTheSame(oldItem: Item, newItem: Item): Boolean {
return oldItem == newItem //Called to decide whether two items have the same data.
}
}
}
//oldItem Value: The item in the old list.
//newItem Value: The item in the new list.
我认为问题不在于您加载新数据的方式,而在于更新数据。虽然您没有向我们展示您触发项目更新的部分或实际更新是如何发生的,但我猜,如果我错了,抱歉,您可能会像这样直接编辑列表元素:
category = adapter.getItemAt(/*item position*/)
category.name = "a new name"
category.color = 5
categoryViewModel.update(category)
相反,您应该创建一个新的 Category
对象而不是修改现有对象,如下所示:
prevCategory = adapter.getItemAt(/*put position*/) // Do not edit prevCategory!
newCategory = Category(id=prevCategory.id, name="a new name", color=5, iconId=0)
categoryViewModel.update(newCategory)
每次您想进行哪怕是最小的更改时都创建一个全新的新对象的想法一开始可能并不那么明显,但是这种反应式实现依赖于每个事件都独立于其他事件的假设。使您的数据 class 不可变,或实际上不可变将防止此问题。
为了避免这种错误,我喜欢做的是,我总是将数据中的每个字段class设为最终字段。
@Entity(tableName = Database.Table.CATEGORIES)
data class Category(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = ID) val id: Long = 0,
@ColumnInfo(name = NAME) val name: String = "",
@ColumnInfo(name = ICON_ID) val iconId: Int = 0,
@ColumnInfo(name = COLOR) @ColorInt val color: Int = DEFAULT_COLOR
)
我已经在 PagedListAdapter 上进行了 RnD,并使用 Room 数据库进行了自定义分页。 单击here,您将找到我的实现。希望对您有所帮助。
谢谢。