FragmentStateAdapter


public abstract class FragmentStateAdapter extends RecyclerView.Adapter implements StatefulAdapter


Similar in behavior to FragmentStatePagerAdapter

Lifecycle within RecyclerView:

Summary

Nested types

@RequiresOptIn(level = RequiresOptIn.Level.WARNING)
public annotation FragmentStateAdapter.ExperimentalFragmentStateAdapterApi

Callback interface for listening to fragment lifecycle changes that happen inside the adapter.

Callback returned by onFragmentPreAdded, onFragmentPreRemoved, onFragmentMaxLifecyclePreUpdated called after the operation ends.

Public constructors

FragmentStateAdapter(
    @NonNull FragmentManager fragmentManager,
    @NonNull Lifecycle lifecycle
)

Public methods

boolean
containsItem(long itemId)

Default implementation works for collections that don't add, move, remove items.

abstract @NonNull Fragment
createFragment(int position)

Provide a new Fragment associated with the specified position.

long
getItemId(int position)

Default implementation works for collections that don't add, move, remove items.

void

Called by RecyclerView when it starts observing this Adapter.

final void
onBindViewHolder(@NonNull FragmentViewHolder holder, int position)

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

final @NonNull FragmentViewHolder
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.

final boolean

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

final void

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

final void

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

void

Registers a FragmentTransactionCallback to listen to fragment lifecycle changes that happen inside the adapter.

final void

Restores adapter state

final @NonNull Parcelable

Saves adapter state

final void
setHasStableIds(boolean hasStableIds)

Indicates whether each item in the data set can be represented with a unique identifier of type java.lang.Long.

void

Unregisters a FragmentTransactionCallback.

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.

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.

abstract int

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

int
getItemViewType(int position)

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

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

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

void

Register a new observer to listen for data changes.

void

Sets the state restoration strategy for the Adapter.

void

Unregister an observer currently listening for data changes.

Public constructors

FragmentStateAdapter

Added in 1.0.0
public FragmentStateAdapter(@NonNull FragmentActivity fragmentActivity)
Parameters
@NonNull FragmentActivity fragmentActivity

if the ViewPager2 lives directly in a FragmentActivity subclass.

FragmentStateAdapter

Added in 1.0.0
public FragmentStateAdapter(@NonNull Fragment fragment)
Parameters
@NonNull Fragment fragment

if the ViewPager2 lives directly in a Fragment subclass.

FragmentStateAdapter

Added in 1.0.0
public FragmentStateAdapter(
    @NonNull FragmentManager fragmentManager,
    @NonNull Lifecycle lifecycle
)
Parameters
@NonNull FragmentManager fragmentManager

of ViewPager2's host

@NonNull Lifecycle lifecycle

of ViewPager2's host

Public methods

containsItem

Added in 1.0.0
public boolean containsItem(long itemId)

Default implementation works for collections that don't add, move, remove items.

When overriding, also override getItemId

createFragment

Added in 1.0.0
public abstract @NonNull Fragment createFragment(int position)

Provide a new Fragment associated with the specified position.

The adapter will be responsible for the Fragment lifecycle:

  • The Fragment will be used to display an item.
  • The Fragment will be destroyed when it gets too far from the viewport, and its state will be saved. When the item is close to the viewport again, a new Fragment will be requested, and a previously saved state will be used to initialize it.

getItemId

public long getItemId(int position)

Default implementation works for collections that don't add, move, remove items.

When overriding, also override containsItem.

If the item is not a part of the collection, return NO_ID.

Parameters
int position

Adapter position

Returns
long

stable item id hasStableIds

onAttachedToRecyclerView

@CallSuper
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.0.0
public final void onBindViewHolder(@NonNull FragmentViewHolder 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 FragmentViewHolder 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.0.0
public final @NonNull FragmentViewHolder 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 FragmentViewHolder

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

onDetachedFromRecyclerView

@CallSuper
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.0.0
public final boolean onFailedToRecycleView(@NonNull FragmentViewHolder 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 FragmentViewHolder 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.0.0
public final void onViewAttachedToWindow(@NonNull FragmentViewHolder 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 FragmentViewHolder holder

Holder of the view being attached

onViewRecycled

Added in 1.0.0
public final void onViewRecycled(@NonNull FragmentViewHolder 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 FragmentViewHolder holder

The ViewHolder for the view being recycled

registerFragmentTransactionCallback

Added in 1.1.0
public void registerFragmentTransactionCallback(
    @NonNull FragmentStateAdapter.FragmentTransactionCallback callback
)

Registers a FragmentTransactionCallback to listen to fragment lifecycle changes that happen inside the adapter.

Parameters
@NonNull FragmentStateAdapter.FragmentTransactionCallback callback

Callback to register

restoreState

Added in 1.1.0
public final void restoreState(@NonNull Parcelable savedState)

Restores adapter state

saveState

Added in 1.1.0
public final @NonNull Parcelable saveState()

Saves adapter state

setHasStableIds

Added in 1.0.0
public final void setHasStableIds(boolean hasStableIds)

Indicates whether each item in the data set can be represented with a unique identifier of type java.lang.Long.

Parameters
boolean hasStableIds

Whether items in data set have unique identifiers or not.

unregisterFragmentTransactionCallback

Added in 1.1.0
public void unregisterFragmentTransactionCallback(
    @NonNull FragmentStateAdapter.FragmentTransactionCallback callback
)

Unregisters a FragmentTransactionCallback.

Parameters
@NonNull FragmentStateAdapter.FragmentTransactionCallback callback

Callback to unregister