What is the difference between swapadapter method and notifydatasetchanged method in Recycler view?

时光毁灭记忆、已成空白 提交于 2019-12-08 15:57:57

问题


I would like to know what exactly is the difference between swapAdapter and notifyDatasetChanged methods of RecylerView? Which one is better to use while modifying the data?


回答1:


As the Documentation reads.

public void swapAdapter (Adapter adapter, boolean removeAndRecycleExistingViews)

Swaps the current adapter with the provided one. It is similar to setAdapter(Adapter) but assumes existing adapter and the new adapter uses the same RecyclerView.ViewHolder and does not clear the RecycledViewPool.

Note that it still calls onAdapterChanged callbacks.

and as for

public final void notifyDataSetChanged ()

Notify any registered observers that the data set has changed.

There are two different classes of data change events, item changes and structural changes. Item changes are when a single item has its data updated but no positional changes have occurred. Structural changes are when items are inserted, removed or moved within the data set.

This event does not specify what about the data set has changed, forcing any observers to assume that all existing items and structure may no longer be valid. LayoutManagers will be forced to fully rebind and relayout all visible views.

RecyclerView will attempt to synthesize visible structural change events for adapters that report that they have stable IDs when this method is used. This can help for the purposes of animation and visual object persistence but individual item views will still need to be rebound and relaid out.

If you are writing an adapter it will always be more efficient to use the more specific change events if you can. Rely on notifyDataSetChanged() as a last resort.

Well i feel the documentation lays it out nicely as to where the difference lies and swapAdapter(ad,true) is a way to change the data whereas notifyDataSetChanged() is a method to notify adapter to redraw its views after the data has been changed.



来源:https://stackoverflow.com/questions/32050210/what-is-the-difference-between-swapadapter-method-and-notifydatasetchanged-metho

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!