什么时候为 recyclerView 使用 hasStableIds true?

ssp*_*der 5 android android-recyclerview

我目前正在使用hasStableIdsof recycler 视图,我有以下观察结果:

1) 当hasStableIds = false

  • 一旦被notifyDataSetChanged()调用,它将使所有视图都变脏并再次回收它们,因此将为每个项目调用onCreateViewHolder()onBindViewHolder()

2) 当hasStableIds = true

  • 一旦被notifyDataSetChanged()调用,它将检查 ids,然后决定是否为 recyclerView 项目创建一个 viewHolder。如果数据集没有改变,那么它只会onBindViewHolder()不再调用onCreateViewHolder()

因此,根据上述行为,我很困惑我们是否应该始终将我们的 recyclerview 与 the 一起使用,hasStableIds = true以便避免再次创建viewholder?或者我们应该在什么特定条件下使用它?

Che*_*pta 1

根据文档

Enables adapter publishes a unique Id/value that can act as a key for the item at a given position in recyclerView.

如果该项目在数据集中重新定位,则为该项目返回的 ID 应该相同。 这使您能够避免在适配器通知更改或执行任何位置操作时突然眨眼

警告!,除非您知道列表项/内容在更新期间不会更改,否则不建议这样做。

Android hasStableIds