-
public abstract class RecyclerView.Adapter<VH extends RecyclerView.ViewHolder>
Base class for an Adapter
Adapters provide a binding from an app-specific data set to views that are displayedwithin a RecyclerView.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description public enum
RecyclerView.Adapter.StateRestorationPolicy
Defines how this Adapter wants to restore its state after a view reconstruction (e.g.configuration change).
-
Method Summary
Modifier and Type Method Description abstract VH
onCreateViewHolder(@NonNull() ViewGroup parent, int viewType)
Called when RecyclerView needs a new ViewHolder of the given type to representan item. abstract void
onBindViewHolder(@NonNull() VH holder, int position)
Called by RecyclerView to display the data at the specified position. void
onBindViewHolder(@NonNull() VH holder, int position, @NonNull() List<Object> payloads)
Called by RecyclerView to display the data at the specified position. int
findRelativeAdapterPositionIn(@NonNull() RecyclerView.Adapter<out RecyclerView.ViewHolder> adapter, @NonNull() RecyclerView.ViewHolder viewHolder, int localPosition)
Returns the position of the given ViewHolder in the given Adapter. final VH
createViewHolder(@NonNull() ViewGroup parent, int viewType)
This method calls onCreateViewHolder to create a new ViewHolder and initializes some private fields to be used by RecyclerView. final void
bindViewHolder(@NonNull() VH holder, int position)
This method internally calls onBindViewHolder to update the ViewHolder contents with the item at the given position and also sets up someprivate fields to be used by RecyclerView. int
getItemViewType(int position)
Return the view type of the item at position
for the purposesof view recycling.void
setHasStableIds(boolean hasStableIds)
Indicates whether each item in the data set can be represented with a unique identifierof type Long. long
getItemId(int position)
Return the stable ID for the item at position
.abstract int
getItemCount()
Returns the total number of items in the data set held by the adapter. final boolean
hasStableIds()
Returns true if this adapter publishes a unique long
value that canact as a key for the item at a given position in the data set.void
onViewRecycled(@NonNull() VH holder)
Called when a view created by this adapter has been recycled. boolean
onFailedToRecycleView(@NonNull() VH holder)
Called by the RecyclerView if a ViewHolder created by this Adapter cannot be recycleddue to its transient state. void
onViewAttachedToWindow(@NonNull() VH holder)
Called when a view created by this adapter has been attached to a window. void
onViewDetachedFromWindow(@NonNull() VH holder)
Called when a view created by this adapter has been detached from its window. final boolean
hasObservers()
Returns true if one or more observers are attached to this adapter. void
registerAdapterDataObserver(@NonNull() RecyclerView.AdapterDataObserver observer)
Register a new observer to listen for data changes. void
unregisterAdapterDataObserver(@NonNull() RecyclerView.AdapterDataObserver observer)
Unregister an observer currently listening for data changes. void
onAttachedToRecyclerView(@NonNull() RecyclerView recyclerView)
Called by RecyclerView when it starts observing this Adapter. void
onDetachedFromRecyclerView(@NonNull() RecyclerView recyclerView)
Called by RecyclerView when it stops observing this Adapter. final void
notifyDataSetChanged()
Notify any registered observers that the data set has changed. final void
notifyItemChanged(int position)
Notify any registered observers that the item at position
has changed.final void
notifyItemChanged(int position, @Nullable() Object payload)
Notify any registered observers that the item at position
has changed withan optional payload object.final void
notifyItemRangeChanged(int positionStart, int itemCount)
Notify any registered observers that the itemCount
items starting atpositionpositionStart
have changed.final void
notifyItemRangeChanged(int positionStart, int itemCount, @Nullable() Object payload)
Notify any registered observers that the itemCount
items starting atpositionpositionStart
have changed.final void
notifyItemInserted(int position)
Notify any registered observers that the item reflected at position
has been newly inserted.final void
notifyItemMoved(int fromPosition, int toPosition)
Notify any registered observers that the item reflected at fromPosition
has been moved totoPosition
.final void
notifyItemRangeInserted(int positionStart, int itemCount)
Notify any registered observers that the currently reflected itemCount
items starting atpositionStart
have been newly inserted.final void
notifyItemRemoved(int position)
Notify any registered observers that the item previously located at position
has been removed from the data set.final void
notifyItemRangeRemoved(int positionStart, int itemCount)
Notify any registered observers that the itemCount
items previouslylocated atpositionStart
have been removed from the data set.void
setStateRestorationPolicy(@NonNull() RecyclerView.Adapter.StateRestorationPolicy strategy)
Sets the state restoration strategy for the Adapter. final RecyclerView.Adapter.StateRestorationPolicy
getStateRestorationPolicy()
Returns when this Adapter wants to restore the state. -
-
Method Detail
-
onCreateViewHolder
@NonNull() abstract VH onCreateViewHolder(@NonNull() ViewGroup parent, int viewType)
Called when RecyclerView needs a new ViewHolder of the given type to representan item.
This new ViewHolder should be constructed with a new View that can represent the itemsof the given type. You can either create a new View manually or inflate it from an XMLlayout file.
The new ViewHolder will be used to display items of the adapter using onBindViewHolder. Since it will be re-used to displaydifferent items in the data set, it is a good idea to cache references to sub views ofthe View to avoid unnecessary findViewById calls.
- Parameters:
parent
- The ViewGroup into which the new View will be added after it is bound toan adapter position.viewType
- The view type of the new View.
-
onBindViewHolder
abstract void onBindViewHolder(@NonNull() VH holder, int position)
Called by RecyclerView to display the data at the specified position. This method shouldupdate the contents of the itemView to reflect the item at the givenposition.
Note that unlike android.widget.ListView, RecyclerView will not call this methodagain if the position of the item changes in the data set unless the item itself isinvalidated or the new position cannot be determined. For this reason, you should onlyuse the
position
parameter while acquiring the related data item insidethis method and should not keep a copy of it. If you need the position of an item lateron (e.g. in a click listener), use getBindingAdapterPosition whichwill have the updated adapter position.Override onBindViewHolder instead if Adapter canhandle efficient partial bind.- Parameters:
holder
- The ViewHolder which should be updated to represent the contents of theitem at the given position in the data set.position
- The position of the item within the adapter's data set.
-
onBindViewHolder
void onBindViewHolder(@NonNull() VH holder, int position, @NonNull() List<Object> payloads)
Called by RecyclerView to display the data at the specified position. This methodshould update the contents of the itemView to reflect the item atthe given position.
Note that unlike android.widget.ListView, RecyclerView will not call this methodagain if the position of the item changes in the data set unless the item itself isinvalidated or the new position cannot be determined. For this reason, you should onlyuse the
position
parameter while acquiring the related data item insidethis method and should not keep a copy of it. If you need the position of an item lateron (e.g. in a click listener), use getBindingAdapterPosition whichwill have the updated adapter position.Partial bind vs full bind:
The payloads parameter is a merge list from notifyItemChanged or notifyItemRangeChanged. If the payloads list is not empty,the ViewHolder is currently bound to old data and Adapter may run an efficient partialupdate using the payload info. If the payload is empty, Adapter must run a full bind.Adapter should not assume that the payload passed in notify methods will be received byonBindViewHolder(). For example when the view is not attached to the screen, thepayload in notifyItemChange() will be simply dropped.
- Parameters:
holder
- The ViewHolder which should be updated to represent the contents of theitem at the given position in the data set.position
- The position of the item within the adapter's data set.payloads
- A non-null list of merged payloads.
-
findRelativeAdapterPositionIn
int findRelativeAdapterPositionIn(@NonNull() RecyclerView.Adapter<out RecyclerView.ViewHolder> adapter, @NonNull() RecyclerView.ViewHolder viewHolder, int localPosition)
Returns the position of the given ViewHolder in the given Adapter.If the given Adapter is not part of this Adapter, NO_POSITION is returned.
- Parameters:
adapter
- The adapter which is a sub adapter of this adapter or itself.viewHolder
- The ViewHolder whose local position in the given adapter will bereturned.
-
createViewHolder
@NonNull() final VH createViewHolder(@NonNull() ViewGroup parent, int viewType)
This method calls onCreateViewHolder to create a new ViewHolder and initializes some private fields to be used by RecyclerView.
-
bindViewHolder
final void bindViewHolder(@NonNull() VH holder, int position)
This method internally calls onBindViewHolder to update the ViewHolder contents with the item at the given position and also sets up someprivate fields to be used by RecyclerView.Adapters that merge other adapters should use bindViewHolder when calling nested adapters so thatRecyclerView can track which adapter bound the ViewHolder to return the correctposition from getBindingAdapterPosition method.They should also overridethe findRelativeAdapterPositionIn method.
- Parameters:
holder
- The view holder whose contents should be updatedposition
- The position of the holder with respect to this adapter
-
getItemViewType
int getItemViewType(int position)
Return the view type of the item at
position
for the purposesof view recycling.The default implementation of this method returns 0, making the assumption ofa single view type for the adapter. Unlike ListView adapters, types need notbe contiguous. Consider using id resources to uniquely identify item view types.
- Parameters:
position
- position to query
-
setHasStableIds
void setHasStableIds(boolean hasStableIds)
Indicates whether each item in the data set can be represented with a unique identifierof type Long.
- Parameters:
hasStableIds
- Whether items in data set have unique identifiers or not.
-
getItemId
long getItemId(int position)
Return the stable ID for the item at
position
. If hasStableIds would return false this method should return NO_ID. The default implementationof this method returns NO_ID.- Parameters:
position
- Adapter position to query
-
getItemCount
abstract int getItemCount()
Returns the total number of items in the data set held by the adapter.
-
hasStableIds
final boolean hasStableIds()
Returns true if this adapter publishes a unique
long
value that canact as a key for the item at a given position in the data set. If that item is relocatedin the data set, the ID returned for that item should be the same.
-
onViewRecycled
void onViewRecycled(@NonNull() VH holder)
Called when a view created by this adapter has been recycled.
A view is recycled when a LayoutManager decides that it no longerneeds to be attached to its parent RecyclerView. This can be because it hasfallen out of visibility or a set of cached views represented by views stillattached to the parent RecyclerView. If an item view has large or expensive databound to it such as large bitmaps, this may be a good place to release thoseresources.
RecyclerView calls this method right before clearing ViewHolder's internal data andsending it to RecycledViewPool. This way, if ViewHolder was holding valid informationbefore being recycled, you can call getBindingAdapterPosition to getits adapter position.
- Parameters:
holder
- The ViewHolder for the view being recycled
-
onFailedToRecycleView
boolean onFailedToRecycleView(@NonNull() VH holder)
Called by the RecyclerView if a ViewHolder created by this Adapter cannot be recycleddue to its transient state. Upon receiving this callback, Adapter can clear theanimation(s) that effect the View's transient state and return
true
so thatthe View can be recycled. Keep in mind that the View in question is already removed fromthe RecyclerView.In some cases, it is acceptable to recycle a View although it has transient state. Mostof the time, this is a case where the transient state will be cleared in onBindViewHolder call when View is rebound to a new position.For this reason, RecyclerView leaves the decision to the Adapter and uses the returnvalue of this method to decide whether the View should be recycled or not.
Note that when all animations are created by ItemAnimator, youshould never receive this callback because RecyclerView keeps those Views as childrenuntil their animations are complete. This callback is useful when children of the itemviews create animations which may not be easy to implement using an ItemAnimator.
You should never fix this issue by calling
holder.itemView.setHasTransientState(false);
unless you've previously calledholder.itemView.setHasTransientState(true);
. EachView.setHasTransientState(true)
call must be matched by aView.setHasTransientState(false)
call, otherwise, the state of the Viewmay become inconsistent. You should always prefer to end or cancel animations that aretriggering the transient state instead of handling it manually.- Parameters:
holder
- The ViewHolder containing the View that could not be recycled due to itstransient state.
-
onViewAttachedToWindow
void onViewAttachedToWindow(@NonNull() VH holder)
Called when a view created by this adapter has been attached to a window.
This can be used as a reasonable signal that the view is about to be seenby the user. If the adapter previously freed any resources in onViewDetachedFromWindow those resources should be restored here.
- Parameters:
holder
- Holder of the view being attached
-
onViewDetachedFromWindow
void onViewDetachedFromWindow(@NonNull() VH holder)
Called when a view created by this adapter has been detached from its window.
Becoming detached from the window is not necessarily a permanent condition;the consumer of an Adapter's views may choose to cache views offscreen while theyare not visible, attaching and detaching them as appropriate.
- Parameters:
holder
- Holder of the view being detached
-
hasObservers
final boolean hasObservers()
Returns true if one or more observers are attached to this adapter.
-
registerAdapterDataObserver
void registerAdapterDataObserver(@NonNull() RecyclerView.AdapterDataObserver observer)
Register a new observer to listen for data changes.
The adapter may publish a variety of events describing specific changes.Not all adapters may support all change types and some may fall back to a generic "something changed" event if more specific data is not available.
Components registering observers with an adapter are responsible for unregistering those observers when finished.
- Parameters:
observer
- Observer to register
-
unregisterAdapterDataObserver
void unregisterAdapterDataObserver(@NonNull() RecyclerView.AdapterDataObserver observer)
Unregister an observer currently listening for data changes.
The unregistered observer will no longer receive events about changesto the adapter.
- Parameters:
observer
- Observer to unregister
-
onAttachedToRecyclerView
void onAttachedToRecyclerView(@NonNull() RecyclerView recyclerView)
Called by RecyclerView when it starts observing this Adapter.
Keep in mind that same adapter may be observed by multiple RecyclerViews.
- Parameters:
recyclerView
- The RecyclerView instance which started observing this adapter.
-
onDetachedFromRecyclerView
void onDetachedFromRecyclerView(@NonNull() RecyclerView recyclerView)
Called by RecyclerView when it stops observing this Adapter.
- Parameters:
recyclerView
- The RecyclerView instance which stopped observing this adapter.
-
notifyDataSetChanged
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 structuralchanges. Item changes are when a single item has its data updated but no positionalchanges have occurred. Structural changes are when items are inserted, removed or movedwithin the data set.
This event does not specify what about the data set has changed, forcingany 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 eventsfor adapters that report that they have stable IDs whenthis method is used. This can help for the purposes of animation and visualobject persistence but individual item views will still need to be reboundand relaid out.If you are writing an adapter it will always be more efficient to use the morespecific change events if you can. Rely on
notifyDataSetChanged()
as a last resort.
-
notifyItemChanged
final void notifyItemChanged(int position)
Notify any registered observers that the item at
position
has changed.Equivalent to callingnotifyItemChanged(position, null);
.This is an item change event, not a structural change event. It indicates that anyreflection of the data at
position
is out of date and should be updated.The item atposition
retains the same identity.- Parameters:
position
- Position of the item that has changed
-
notifyItemChanged
final void notifyItemChanged(int position, @Nullable() Object payload)
Notify any registered observers that the item at
position
has changed withan optional payload object.This is an item change event, not a structural change event. It indicates that anyreflection of the data at
position
is out of date and should be updated.The item atposition
retains the same identity.Client can optionally pass a payload for partial change. These payloads will be mergedand may be passed to adapter's onBindViewHolder if theitem is already represented by a ViewHolder and it will be rebound to the sameViewHolder. A notifyItemRangeChanged() with null payload will clear all existingpayloads on that item and prevent future payload until onBindViewHolder is called. Adapter should not assumethat the payload will always be passed to onBindViewHolder(), e.g. when the view is notattached, the payload will be simply dropped.
- Parameters:
position
- Position of the item that has changedpayload
- Optional parameter, use null to identify a "full" update
-
notifyItemRangeChanged
final void notifyItemRangeChanged(int positionStart, int itemCount)
Notify any registered observers that the
itemCount
items starting atpositionpositionStart
have changed.Equivalent to callingnotifyItemRangeChanged(position, itemCount, null);
.This is an item change event, not a structural change event. It indicates thatany reflection of the data in the given position range is out of date and shouldbe updated. The items in the given range retain the same identity.
- Parameters:
positionStart
- Position of the first item that has changeditemCount
- Number of items that have changed
-
notifyItemRangeChanged
final void notifyItemRangeChanged(int positionStart, int itemCount, @Nullable() Object payload)
Notify any registered observers that the
itemCount
items starting atpositionpositionStart
have changed. An optional payload can bepassed to each changed item.This is an item change event, not a structural change event. It indicates that anyreflection of the data in the given position range is out of date and should be updated.The items in the given range retain the same identity.
Client can optionally pass a payload for partial change. These payloads will be mergedand may be passed to adapter's onBindViewHolder if theitem is already represented by a ViewHolder and it will be rebound to the sameViewHolder. A notifyItemRangeChanged() with null payload will clear all existingpayloads on that item and prevent future payload until onBindViewHolder is called. Adapter should not assumethat the payload will always be passed to onBindViewHolder(), e.g. when the view is notattached, the payload will be simply dropped.
- Parameters:
positionStart
- Position of the first item that has changeditemCount
- Number of items that have changedpayload
- Optional parameter, use null to identify a "full" update
-
notifyItemInserted
final void notifyItemInserted(int position)
Notify any registered observers that the item reflected at
position
has been newly inserted. The item previously atposition
is now atpositionposition + 1
.This is a structural change event. Representations of other existing items in thedata set are still considered up to date and will not be rebound, though theirpositions may be altered.
- Parameters:
position
- Position of the newly inserted item in the data set
-
notifyItemMoved
final void notifyItemMoved(int fromPosition, int toPosition)
Notify any registered observers that the item reflected at
fromPosition
has been moved totoPosition
.This is a structural change event. Representations of other existing items in thedata set are still considered up to date and will not be rebound, though theirpositions may be altered.
- Parameters:
fromPosition
- Previous position of the item.toPosition
- New position of the item.
-
notifyItemRangeInserted
final void notifyItemRangeInserted(int positionStart, int itemCount)
Notify any registered observers that the currently reflected
itemCount
items starting atpositionStart
have been newly inserted. The itemspreviously located atpositionStart
and beyond can now be found startingat positionpositionStart + itemCount
.This is a structural change event. Representations of other existing items in thedata set are still considered up to date and will not be rebound, though their positionsmay be altered.
- Parameters:
positionStart
- Position of the first item that was inserteditemCount
- Number of items inserted
-
notifyItemRemoved
final void notifyItemRemoved(int position)
Notify any registered observers that the item previously located at
position
has been removed from the data set. The items previously located at and afterposition
may now be found atoldPosition - 1
.This is a structural change event. Representations of other existing items in thedata set are still considered up to date and will not be rebound, though their positionsmay be altered.
- Parameters:
position
- Position of the item that has now been removed
-
notifyItemRangeRemoved
final void notifyItemRangeRemoved(int positionStart, int itemCount)
Notify any registered observers that the
itemCount
items previouslylocated atpositionStart
have been removed from the data set. The itemspreviously located at and afterpositionStart + itemCount
may now be foundatoldPosition - itemCount
.This is a structural change event. Representations of other existing items in the dataset are still considered up to date and will not be rebound, though their positionsmay be altered.
- Parameters:
positionStart
- Previous position of the first item that was removeditemCount
- Number of items removed from the data set
-
setStateRestorationPolicy
void setStateRestorationPolicy(@NonNull() RecyclerView.Adapter.StateRestorationPolicy strategy)
Sets the state restoration strategy for the Adapter.By default, it is set to ALLOW which means RecyclerViewexpects any set Adapter to be immediately capable of restoring the RecyclerView's savedscroll position.
This behaviour might be undesired if the Adapter's data is loaded asynchronously, andthus unavailable during initial layout (e.g. after Activity rotation). To avoid losingscroll position, you can change this to be either PREVENT_WHEN_EMPTY or PREVENT.Note that the former means your RecyclerView will restore state as soon as Adapter has1 or more items while the latter requires you to call setStateRestorationPolicy with either ALLOW or PREVENT_WHEN_EMPTY again when the Adapter isready to restore its state.
RecyclerView will still layout even when State restoration is disabled. The behavior ofhow State is restored is up to the LayoutManager. All default LayoutManagerswill override current state with restored state when state restoration happens (unlessan explicit call to scrollToPosition is made).
Calling this method after state is restored will not have any effect other than changingthe return value of getStateRestorationPolicy.
- Parameters:
strategy
- The saved state restoration strategy for this Adapter.
-
getStateRestorationPolicy
@NonNull() final RecyclerView.Adapter.StateRestorationPolicy getStateRestorationPolicy()
Returns when this Adapter wants to restore the state.
-
-
-
-