欢迎参加我们将于 6 月 3 日举行的 #Android11:Beta 版发布会

MergeAdapter

public final class MergeAdapter
extends Adapter<RecyclerView.ViewHolder>

java.lang.Object
   ↳ androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>
     ↳ androidx.recyclerview.widget.MergeAdapter


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

 MyAdapter adapter1 = ...;
 AnotherAdapter adapter2 = ...;
 MergeAdapter merged = new MergeAdapter(adapter1, adapter2);
 recyclerView.setAdapter(mergedAdapter);
 

By default, MergeAdapter 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 RecyclerView.ViewHolders, with no re-use in between added adapters.

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

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

Whether MergeAdapter should support stable ids is defined in the MergeAdapter.Config object. Calling RecyclerView.Adapter.setHasStableIds(boolean) has no effect. See documentation for MergeAdapter.Config.StableIdMode for details on how to configure MergeAdapter 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 RecyclerView.ViewHolder to handle user action on the RecyclerView.ViewHolder. For those cases, instead of calling RecyclerView.ViewHolder.getAdapterPosition(), use RecyclerView.ViewHolder.getBindingAdapterPosition(). If your adapters share RecyclerView.ViewHolders, you can use the RecyclerView.ViewHolder.getBindingAdapter() method to find the adapter which last bound that RecyclerView.ViewHolder.

Summary

Nested classes

class MergeAdapter.Config

The configuration object for a MergeAdapter

Public constructors

MergeAdapter(Adapter...<? extends RecyclerView.ViewHolder> adapters)

Creates a MergeAdapter with MergeAdapter.Config.DEFAULT and the given adapters in the given order.

MergeAdapter(MergeAdapter.Config config, Adapter...<? extends RecyclerView.ViewHolder> adapters)

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

MergeAdapter(List<Adapter<? extends RecyclerView.ViewHolder>> adapters)

Creates a MergeAdapter with MergeAdapter.Config.DEFAULT and the given adapters in the given order.

MergeAdapter(MergeAdapter.Config config, List<Adapter<? extends RecyclerView.ViewHolder>> adapters)

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

Public methods

boolean addAdapter(Adapter<? extends RecyclerView.ViewHolder> adapter)

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

boolean addAdapter(int index, Adapter<? extends RecyclerView.ViewHolder> adapter)

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

int findRelativeAdapterPositionIn(Adapter<? extends RecyclerView.ViewHolder> adapter, RecyclerView.ViewHolder viewHolder, int globalPosition)

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

List<Adapter<? extends RecyclerView.ViewHolder>> getAdapters()

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

int getItemCount()

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.

void onAttachedToRecyclerView(RecyclerView recyclerView)

Called by RecyclerView when it starts observing this Adapter.

void onBindViewHolder(RecyclerView.ViewHolder holder, int position)

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

RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)

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

void onDetachedFromRecyclerView(RecyclerView recyclerView)

Called by RecyclerView when it stops observing this Adapter.

boolean onFailedToRecycleView(RecyclerView.ViewHolder holder)

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

void onViewAttachedToWindow(RecyclerView.ViewHolder holder)

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

void onViewDetachedFromWindow(RecyclerView.ViewHolder holder)

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

void onViewRecycled(RecyclerView.ViewHolder holder)

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

boolean removeAdapter(Adapter<? extends RecyclerView.ViewHolder> adapter)

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 setStateRestorationPolicy(RecyclerView.Adapter.StateRestorationPolicy strategy)

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

Inherited methods

Public constructors

MergeAdapter

public MergeAdapter (Adapter...<? extends RecyclerView.ViewHolder> adapters)

Creates a MergeAdapter with MergeAdapter.Config.DEFAULT and the given adapters in the given order.

Parameters
adapters Adapter: The list of adapters to add

MergeAdapter

public MergeAdapter (MergeAdapter.Config config, 
                Adapter...<? extends RecyclerView.ViewHolder> adapters)

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

Parameters
config MergeAdapter.Config: The configuration for this MergeAdapter

adapters Adapter: The list of adapters to add

MergeAdapter

public MergeAdapter (List<Adapter<? extends RecyclerView.ViewHolder>> adapters)

Creates a MergeAdapter with MergeAdapter.Config.DEFAULT and the given adapters in the given order.

Parameters
adapters List: The list of adapters to add

MergeAdapter

public MergeAdapter (MergeAdapter.Config config, 
                List<Adapter<? extends RecyclerView.ViewHolder>> adapters)

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

Parameters
config MergeAdapter.Config: The configuration for this MergeAdapter

adapters List: The list of adapters to add

Public methods

addAdapter

public boolean addAdapter (Adapter<? extends RecyclerView.ViewHolder> adapter)

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

Parameters
adapter Adapter: The new adapter to add

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

addAdapter

public boolean addAdapter (int index, 
                Adapter<? extends RecyclerView.ViewHolder> adapter)

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

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

adapter 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 (Adapter<? extends RecyclerView.ViewHolder> adapter, 
                RecyclerView.ViewHolder viewHolder, 
                int globalPosition)

Returns the position of the given RecyclerView.ViewHolder in the given RecyclerView.Adapter. If the given RecyclerView.Adapter is not part of this MergeAdapter, RecyclerView.NO_POSITION is returned.

Parameters
adapter Adapter: The adapter which is a sub adapter of this MergeAdapter or itself.

viewHolder RecyclerView.ViewHolder: The view holder whose local position in the given adapter will be returned.

globalPosition int

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

getAdapters

public List<Adapter<? extends RecyclerView.ViewHolder>> getAdapters ()

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

Returns
List<Adapter<? extends RecyclerView.ViewHolder>> A copy of the list of adapters in this MergeAdapter.

getItemCount

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 RecyclerView.NO_ID. The default implementation of this method returns RecyclerView.NO_ID.

Parameters
position int: 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
position int: 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.

onAttachedToRecyclerView

public void onAttachedToRecyclerView (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 RecyclerView: The RecyclerView instance which started observing this adapter.

onBindViewHolder

public void onBindViewHolder (RecyclerView.ViewHolder holder, 
                int position)

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

Note that unlike 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 RecyclerView.ViewHolder.getBindingAdapterPosition() which will have the updated adapter position. Override onBindViewHolder(ViewHolder, int, List) instead if Adapter can handle efficient partial bind.

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

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

onCreateViewHolder

public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent, 
                int viewType)

Called when RecyclerView needs a new RecyclerView.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(ViewHolder, int, List). 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 View.findViewById(int) calls.

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

viewType int: The view type of the new View.

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

onDetachedFromRecyclerView

public void onDetachedFromRecyclerView (RecyclerView recyclerView)

Called by RecyclerView when it stops observing this Adapter.

Parameters
recyclerView RecyclerView: The RecyclerView instance which stopped observing this adapter.

onFailedToRecycleView

public boolean onFailedToRecycleView (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(ViewHolder, int) 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 RecyclerView.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
holder RecyclerView.ViewHolder: 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

public void onViewAttachedToWindow (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
holder RecyclerView.ViewHolder: Holder of the view being attached

onViewDetachedFromWindow

public void onViewDetachedFromWindow (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
holder RecyclerView.ViewHolder: Holder of the view being detached

onViewRecycled

public void onViewRecycled (RecyclerView.ViewHolder holder)

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

A view is recycled when a RecyclerView.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 RecyclerView.ViewHolder.getBindingAdapterPosition() to get its adapter position.

Parameters
holder RecyclerView.ViewHolder: The ViewHolder for the view being recycled

removeAdapter

public boolean removeAdapter (Adapter<? extends RecyclerView.ViewHolder> adapter)

Removes the given adapter from the adapters list if it exists

Parameters
adapter Adapter: The adapter to remove

Returns
boolean true if the adapter was previously added to this MergeAdapter 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 MergeAdapter.Config object passed into the MergeAdapter to configure this behavior.

Parameters
hasStableIds boolean: Whether items in data set have unique identifiers or not.

setStateRestorationPolicy

public void setStateRestorationPolicy (RecyclerView.Adapter.StateRestorationPolicy strategy)

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

Parameters
strategy RecyclerView.Adapter.StateRestorationPolicy: The saved state restoration strategy for this Adapter such that MergeAdapter will allow state restoration only if all added adapters allow it or there are no adapters.