android - ContentObserver 可以与新的 RecyclerView notifyItem 函数一起使用吗?

标签 android android-adapter android-recyclerview android-cursor

我正在努力弄清楚如何利用 RecyclerView.Adapter

中的一组扩展通知函数
final void notifyItemChanged(int position)
final void notifyItemInserted(int position)
final void notifyItemMoved(int fromPosition, int toPosition)
final void notifyItemRangeChanged(int positionStart, int itemCount)
final void notifyItemRangeInserted(int positionStart, int itemCount)
final void notifyItemRangeRemoved(int positionStart, int itemCount)
final void notifyItemRemoved(int position)

这是我的推理:

如果我使用 ContentProvider 填充我的 RecyclerView,并使用 ContentObserver 通知我的 RecyclerView 适配器数据集更改,ContentObserver 只有 onChange(boolean self, Uri uri) 来传达更改到适配器。仅此函数无法提供足够的信息来正确区分应使用哪个 notifyItem..... 函数。

RecyclerView Adapter 的这些通知函数是否要与 ContentObserver 一起使用?或者它们打算以其他方式使用?

谢谢!

最佳答案

来自 a reddit post , 感谢原作者 defer .

  1. Make the cursor swapable (i.e. add a swapCursor(Cursor) method to your adapter that changes the stored cursor and then calls notifyDataSetChanged()).
  2. setHasStableIds(true) in the adapter
  3. Override getItemId() in the adapter to provide a unique id for each position, these unique ids should map directly to your database ids which means that the adapter can easily cross-reference them with previous states of the cursor.
  4. When your content changes just call your new swapCursor method with the new cursor and it will use the unique ids to map the previous state to the new one and automatically compute the appropriate animations.

Edit: I'm assuming you have a cursor, in fact it works with any underlying data structure, the key is setHasStableIds, overriding the getItemId function and calling notifyDataSetChanged.

关于android - ContentObserver 可以与新的 RecyclerView notifyItem 函数一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30468062/

相关文章:

android - 创建 Intent 的最佳实践

java - 在 MVP 结构中,哪个类负责保留列表项以及如何通知此中的数据更改

android - 如何从 RecyclerView Adapter 调用 ViewModel.delete?

android - 回收站 View 未显示

android - Google Play 应用签名流程

java - Flutter 在启动时崩溃 : Didn't find class . MainActivity 在路径 DexPathList 上

android - 通过 NFC 将 URL 从 Android 发送到 Windows Phone 会提供 Play Store 链接

android - 当我按下手机上的按钮时应用程序崩溃

android - 将数据从 RecyclerView Adapter 传递到 Parent Fragment

java - 卡片 View 未出现在 RecyclerView 中