1.在调用Adapter的notifyDataSetChanged后,看下面代码的注释:
/**
* Notify any registered observers that the data set has changed.
*
* <p>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.</p>
*
* <p>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.</p>
*
* <p><code>RecyclerView</code> will attempt to synthesize visible structural change events
* for adapters that report that they have {@link #hasStableIds() 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.</p>
*
* <p>If you are writing an adapter it will always be more efficient to use the more
* specific change events if you can. Rely on <code>notifyDataSetChanged()</code>
* as a last resort.</p>
*
* @see #notifyItemChanged(int)
* @see #notifyItemInserted(int)
* @see #notifyItemRemoved(int)
* @see #notifyItemRangeChanged(int, int)
* @see #notifyItemRangeInserted(int, int)
* @see #notifyItemRangeRemoved(int, int)
*/
public final void notifyDataSetChanged() {
mObservable.notifyChanged();
}
可以看出,在调用notifyDataSetChanged后,调用Recyclerview的getChildAdapterPosition(view)就会返回-1,这时要使用getChildLayoutPosition(view)可以拿到layout之前的对应view的位置,getChildAdapterPosition(view)和getChildLayoutPosition(view)本质上调用的是ViewHolder的getAdapterPosition()和getLayoutPosition()方法。二者区别如下:
(1)getLayoutPosition():返回的一直是界面上呈现的 Item 的位置信息,即使某个 Item 已经从数据源中被移除。
(2)getAdapterPosition():当数据源发生变化,且界面已经刷新过后即 onBindViewHolder() 已经被调用了后,返回的值跟 getLayoutPosition() 一致;但当数据源发生变化,且在 onBindViewHolder() 被调用之前,如果调用了 notifyDataSetChanged(), 那么将返回无效的位置标志 -1;如果调用了 notifyItem系列(),那么将返回 Item 在数据源中的位置信息。