ConcatAdapter

public final class ConcatAdapter extends RecyclerView.Adapter


An Adapter implementation that presents the contents of multiple adapters in sequence.

MyAdapter adapter1 = ...;
AnotherAdapter adapter2 = ...;
ConcatAdapter concatenated = new ConcatAdapter(adapter1, adapter2);
recyclerView.setAdapter(concatenated);

By default, ConcatAdapter isolates view types of nested adapters from each other such that it will change the view type before reporting it back to the RecyclerView to avoid any conflicts between the view types of added adapters. This also means each added adapter will have its own isolated pool of ViewHolders, with no re-use in between added adapters.

If your Adapters share the same view types, and can support sharing ViewHolder s between added adapters, provide an instance of Config where you set isolateViewTypes to false. A common usage pattern for this is to return the R.layout.<layout_name> from the getItemViewType method.

When an added adapter calls one of the notify methods, ConcatAdapter properly offsets values before reporting it back to the RecyclerView. If an adapter calls notifyDataSetChanged, ConcatAdapter also calls notifyDataSetChanged as calling notifyItemRangeChanged will confuse the RecyclerView. You are highly encouraged to to use SortedList or ListAdapter to avoid calling notifyDataSetChanged.

Whether ConcatAdapter should support stable ids is defined in the Config object. Calling setHasStableIds has no effect. See documentation for Config.StableIdMode for details on how to configure ConcatAdapter to use stable ids. By default, it will not use stable ids and sub adapter stable ids will be ignored. Similar to the case above, you are highly encouraged to use ListAdapter, which will automatically calculate the changes in the data set for you so you won't need stable ids.

It is common to find the adapter position of a ViewHolder to handle user action on the ViewHolder. For those cases, instead of calling getAdapterPosition, use getBindingAdapterPosition. If your adapters share ViewHolders, you can use the getBindingAdapter method to find the adapter which last bound that ViewHolder.

Summary

Nested types

public final class ConcatAdapter.Config

The configuration object for a ConcatAdapter.

public final class ConcatAdapter.Config.Builder

The builder for Config class.

Defines how ConcatAdapter handle stable ids (hasStableIds).

Public constructors

@SafeVarargs
ConcatAdapter(@NonNull RecyclerView.Adapter[] adapters)

Creates a ConcatAdapter with DEFAULT and the given adapters in the given order.

Creates a ConcatAdapter with DEFAULT and the given adapters in the given order.

@SafeVarargs
ConcatAdapter(
    @NonNull ConcatAdapter.Config config,
    @NonNull RecyclerView.Adapter[] adapters
)

Creates a ConcatAdapter with the given config and the given adapters in the given order.

Creates a ConcatAdapter with the given config and the given adapters in the given order.

Public methods

boolean

Appends the given adapter to the existing list of adapters and notifies the observers of this ConcatAdapter.

boolean
addAdapter(
    int index,
    @NonNull RecyclerView.Adapter<RecyclerView.ViewHolder> adapter
)

Adds the given adapter to the given index among other adapters that are already added.

int
findRelativeAdapterPositionIn(
    @NonNull RecyclerView.Adapter<RecyclerView.ViewHolder> adapter,
    @NonNull RecyclerView.ViewHolder viewHolder,
    int localPosition
)

Returns the position of the given ViewHolder in the given Adapter.

@NonNull List<RecyclerView.Adapter<RecyclerView.ViewHolder>>

Returns an unmodifiable copy of the list of adapters in this ConcatAdapter.

int

Returns the total number of items in the data set held by the adapter.

long
getItemId(int position)

Return the stable ID for the item at position.

int
getItemViewType(int position)

Return the view type of the item at position for the purposes of view recycling.

@NonNull Pair<RecyclerView.Adapter<RecyclerView.ViewHolder>, Integer>
getWrappedAdapterAndPosition(int globalPosition)

Retrieve the adapter and local position for a given position in this ConcatAdapter.

void

Called by RecyclerView when it starts observing this Adapter.

void

Called by RecyclerView to display the data at the specified position.

@NonNull RecyclerView.ViewHolder
onCreateViewHolder(@NonNull ViewGroup parent, int viewType)

Called when RecyclerView needs a new ViewHolder of the given type to represent an item.

void

Called by RecyclerView when it stops observing this Adapter.

boolean

Called by the RecyclerView if a ViewHolder created by this Adapter cannot be recycled due to its transient state.

void

Called when a view created by this adapter has been attached to a window.

void

Called when a view created by this adapter has been detached from its window.

void

Called when a view created by this adapter has been recycled.

boolean

Removes the given adapter from the adapters list if it exists

void
setHasStableIds(boolean hasStableIds)

Calling this method is an error and will result in an UnsupportedOperationException.

void

Calling this method is an error and will result in an UnsupportedOperationException.

Inherited methods

From androidx.recyclerview.widget.RecyclerView.Adapter
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 some private fields to be used by RecyclerView.

final @NonNull 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 @NonNull RecyclerView.Adapter.StateRestorationPolicy

Returns when this Adapter wants to restore the state.

final boolean

Returns true if one or more observers are attached to this adapter.

final boolean

Returns true if this adapter publishes a unique long value that can act as a key for the item at a given position in the data set.

final void

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 with an optional payload object.

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 to toPosition.

final void
notifyItemRangeChanged(int positionStart, int itemCount)

Notify any registered observers that the itemCount items starting at position positionStart have changed.

final void
notifyItemRangeChanged(
    int positionStart,
    int itemCount,
    @Nullable Object payload
)

Notify any registered observers that the itemCount items starting at position positionStart have changed.

final void
notifyItemRangeInserted(int positionStart, int itemCount)

Notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted.

final void
notifyItemRangeRemoved(int positionStart, int itemCount)

Notify any registered observers that the itemCount items previously located at positionStart have been removed from the data set.

final void
notifyItemRemoved(int position)

Notify any registered observers that the item previously located at position has been removed from the data set.

void
onBindViewHolder(
    @NonNull VH holder,
    int position,
    @NonNull List<Object> payloads
)

Called by RecyclerView to display the data at the specified position.

void

Register a new observer to listen for data changes.

void

Unregister an observer currently listening for data changes.

Public constructors

ConcatAdapter

@SafeVarargs
public ConcatAdapter(@NonNull RecyclerView.Adapter[] adapters)

Creates a ConcatAdapter with DEFAULT and the given adapters in the given order.

Parameters
@NonNull RecyclerView.Adapter[] adapters

The list of adapters to add

ConcatAdapter

Added in 1.2.0
public ConcatAdapter(
    @NonNull List<RecyclerView.Adapter<RecyclerView.ViewHolder>> adapters
)

Creates a ConcatAdapter with DEFAULT and the given adapters in the given order.

Parameters
@NonNull List<RecyclerView.Adapter<RecyclerView.ViewHolder>> adapters

The list of adapters to add

ConcatAdapter

@SafeVarargs
public ConcatAdapter(
    @NonNull ConcatAdapter.Config config,
    @NonNull RecyclerView.Adapter[] adapters
)

Creates a ConcatAdapter with the given config and the given adapters in the given order.

Parameters
@NonNull ConcatAdapter.Config config

The configuration for this ConcatAdapter

@NonNull RecyclerView.Adapter[] adapters

The list of adapters to add

ConcatAdapter

Added in 1.2.0
public ConcatAdapter(
    @NonNull ConcatAdapter.Config config,
    @NonNull List<RecyclerView.Adapter<RecyclerView.ViewHolder>> adapters
)

Creates a ConcatAdapter with the given config and the given adapters in the given order.

Parameters
@NonNull ConcatAdapter.Config config

The configuration for this ConcatAdapter

@NonNull List<RecyclerView.Adapter<RecyclerView.ViewHolder>> adapters

The list of adapters to add

Public methods

addAdapter

Added in 1.2.0
public boolean addAdapter(
    @NonNull RecyclerView.Adapter<RecyclerView.ViewHolder> adapter
)

Appends the given adapter to the existing list of adapters and notifies the observers of this ConcatAdapter.

Parameters
@NonNull RecyclerView.Adapter<RecyclerView.ViewHolder> adapter

The new adapter to add

Returns
boolean

true if the adapter is successfully added because it did not already exist, false otherwise.

addAdapter

Added in 1.2.0
public boolean addAdapter(
    int index,
    @NonNull RecyclerView.Adapter<RecyclerView.ViewHolder> adapter
)

Adds the given adapter to the given index among other adapters that are already added.

Parameters
int index

The index into which to insert the adapter. ConcatAdapter will throw an IndexOutOfBoundsException if the index is not between 0 and current adapter count (inclusive).

@NonNull RecyclerView.Adapter<RecyclerView.ViewHolder> adapter

The new adapter to add to the adapters list.

Returns
boolean

true if the adapter is successfully added because it did not already exist, false otherwise.

findRelativeAdapterPositionIn

public int findRelativeAdapterPositionIn(
    @NonNull RecyclerView.Adapter<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 ConcatAdapter, NO_POSITION is returned.

Parameters
@NonNull RecyclerView.Adapter<RecyclerView.ViewHolder> adapter

The adapter which is a sub adapter of this ConcatAdapter or itself.

@NonNull RecyclerView.ViewHolder viewHolder

The view holder whose local position in the given adapter will be returned.

int localPosition

The position of the given ViewHolder in this Adapter.

Returns
int

The local position of the given ViewHolder in the given Adapter or NO_POSITION if the ViewHolder is not bound to an item or the given Adapter is not part of this ConcatAdapter.

getAdapters

Added in 1.2.0
public @NonNull List<RecyclerView.Adapter<RecyclerView.ViewHolder>> getAdapters()

Returns an unmodifiable copy of the list of adapters in this ConcatAdapter. Note that this is a copy hence future changes in the ConcatAdapter are not reflected in this list.

Returns
@NonNull List<RecyclerView.Adapter<RecyclerView.ViewHolder>>

A copy of the list of adapters in this ConcatAdapter.

getItemCount

Added in 1.4.0-alpha01
public int getItemCount()

Returns the total number of items in the data set held by the adapter.

Returns
int

The total number of items in this adapter.

getItemId

public 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 implementation of this method returns NO_ID.

Parameters
int position

Adapter position to query

Returns
long

the stable ID of the item at position

getItemViewType

public int getItemViewType(int position)

Return the view type of the item at position for the purposes of view recycling.

The default implementation of this method returns 0, making the assumption of a single view type for the adapter. Unlike ListView adapters, types need not be contiguous. Consider using id resources to uniquely identify item view types.

Parameters
int position

position to query

Returns
int

integer value identifying the type of the view needed to represent the item at position. Type codes need not be contiguous.

getWrappedAdapterAndPosition

Added in 1.3.0
public @NonNull Pair<RecyclerView.Adapter<RecyclerView.ViewHolder>, IntegergetWrappedAdapterAndPosition(int globalPosition)

Retrieve the adapter and local position for a given position in this ConcatAdapter. This allows for retrieving wrapped adapter information in situations where you don't have a ViewHolder, such as within a androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup in which you want to look up information from the source adapter.

Parameters
int globalPosition

The position in this ConcatAdapter.

Returns
@NonNull Pair<RecyclerView.Adapter<RecyclerView.ViewHolder>, Integer>

a Pair with the first element set to the wrapped Adapter containing that position and the second element set to the local position in the wrapped adapter

Throws
java.lang.IllegalArgumentException

if the specified globalPosition does not correspond to a valid element of this adapter. That is, if globalPosition is less than 0 or greater than the total number of items in the ConcatAdapter

onAttachedToRecyclerView

public 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
@NonNull RecyclerView recyclerView

The RecyclerView instance which started observing this adapter.

onBindViewHolder

Added in 1.2.0
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position)

Called by RecyclerView to display the data at the specified position. This method should update the contents of the itemView to reflect the item at the given position.

Note that unlike android.widget.ListView, RecyclerView will not call this method again if the position of the item changes in the data set unless the item itself is invalidated or the new position cannot be determined. For this reason, you should only use the position parameter while acquiring the related data item inside this method and should not keep a copy of it. If you need the position of an item later on (e.g. in a click listener), use getBindingAdapterPosition which will have the updated adapter position. Override onBindViewHolder instead if Adapter can handle efficient partial bind.

Parameters
@NonNull RecyclerView.ViewHolder holder

The ViewHolder which should be updated to represent the contents of the item at the given position in the data set.

int position

The position of the item within the adapter's data set.

onCreateViewHolder

Added in 1.4.0-alpha01
public @NonNull RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)

Called when RecyclerView needs a new ViewHolder of the given type to represent an item.

This new ViewHolder should be constructed with a new View that can represent the items of the given type. You can either create a new View manually or inflate it from an XML layout file.

The new ViewHolder will be used to display items of the adapter using onBindViewHolder. Since it will be re-used to display different items in the data set, it is a good idea to cache references to sub views of the View to avoid unnecessary findViewById calls.

Parameters
@NonNull ViewGroup parent

The ViewGroup into which the new View will be added after it is bound to an adapter position.

int viewType

The view type of the new View.

Returns
@NonNull RecyclerView.ViewHolder

A new ViewHolder that holds a View of the given view type.

onDetachedFromRecyclerView

public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView)

Called by RecyclerView when it stops observing this Adapter.

Parameters
@NonNull RecyclerView recyclerView

The RecyclerView instance which stopped observing this adapter.

onFailedToRecycleView

Added in 1.2.0
public boolean onFailedToRecycleView(@NonNull RecyclerView.ViewHolder holder)

Called by the RecyclerView if a ViewHolder created by this Adapter cannot be recycled due to its transient state. Upon receiving this callback, Adapter can clear the animation(s) that effect the View's transient state and return true so that the View can be recycled. Keep in mind that the View in question is already removed from the RecyclerView.

In some cases, it is acceptable to recycle a View although it has transient state. Most of 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 return value of this method to decide whether the View should be recycled or not.

Note that when all animations are created by RecyclerView.ItemAnimator, you should never receive this callback because RecyclerView keeps those Views as children until their animations are complete. This callback is useful when children of the item views 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 called holder.itemView.setHasTransientState(true);. Each View.setHasTransientState(true) call must be matched by a View.setHasTransientState(false) call, otherwise, the state of the View may become inconsistent. You should always prefer to end or cancel animations that are triggering the transient state instead of handling it manually.

Parameters
@NonNull RecyclerView.ViewHolder holder

The ViewHolder containing the View that could not be recycled due to its transient state.

Returns
boolean

True if the View should be recycled, false otherwise. Note that if this method returns true, RecyclerView will ignore the transient state of the View and recycle it regardless. If this method returns false, RecyclerView will check the View's transient state again before giving a final decision. Default implementation returns false.

onViewAttachedToWindow

Added in 1.2.0
public void onViewAttachedToWindow(@NonNull RecyclerView.ViewHolder 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 seen by the user. If the adapter previously freed any resources in onViewDetachedFromWindow those resources should be restored here.

Parameters
@NonNull RecyclerView.ViewHolder holder

Holder of the view being attached

onViewDetachedFromWindow

Added in 1.2.0
public void onViewDetachedFromWindow(@NonNull RecyclerView.ViewHolder 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 they are not visible, attaching and detaching them as appropriate.

Parameters
@NonNull RecyclerView.ViewHolder holder

Holder of the view being detached

onViewRecycled

Added in 1.2.0
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder)

Called when a view created by this adapter has been recycled.

A view is recycled when a LayoutManager decides that it no longer needs to be attached to its parent RecyclerView. This can be because it has fallen out of visibility or a set of cached views represented by views still attached to the parent RecyclerView. If an item view has large or expensive data bound to it such as large bitmaps, this may be a good place to release those resources.

RecyclerView calls this method right before clearing ViewHolder's internal data and sending it to RecycledViewPool. This way, if ViewHolder was holding valid information before being recycled, you can call getBindingAdapterPosition to get its adapter position.

Parameters
@NonNull RecyclerView.ViewHolder holder

The ViewHolder for the view being recycled

removeAdapter

Added in 1.2.0
public boolean removeAdapter(
    @NonNull RecyclerView.Adapter<RecyclerView.ViewHolder> adapter
)

Removes the given adapter from the adapters list if it exists

Parameters
@NonNull RecyclerView.Adapter<RecyclerView.ViewHolder> adapter

The adapter to remove

Returns
boolean

true if the adapter was previously added to this ConcatAdapter and now removed or false if it couldn't be found.

setHasStableIds

public void setHasStableIds(boolean hasStableIds)

Calling this method is an error and will result in an UnsupportedOperationException. You should use the Config object passed into the ConcatAdapter to configure this behavior.

Parameters
boolean hasStableIds

Whether items in data set have unique identifiers or not.

setStateRestorationPolicy

public void setStateRestorationPolicy(
    @NonNull RecyclerView.Adapter.StateRestorationPolicy strategy
)

Calling this method is an error and will result in an UnsupportedOperationException. ConcatAdapter infers this value from added Adapters.

Parameters
@NonNull RecyclerView.Adapter.StateRestorationPolicy strategy

The saved state restoration strategy for this Adapter such that ConcatAdapter will allow state restoration only if all added adapters allow it or there are no adapters.