我正在努力弄清楚如何利用 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 .
- Make the cursor swapable (i.e. add a
swapCursor(Cursor)
method to your adapter that changes the stored cursor and then callsnotifyDataSetChanged()
).setHasStableIds(true)
in the adapter- 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.- 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 thegetItemId
function and callingnotifyDataSetChanged
.
关于android - ContentObserver 可以与新的 RecyclerView notifyItem 函数一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30468062/