RecyclerView


public class RecyclerView extends ViewGroup implements ScrollingView, NestedScrollingChild2, NestedScrollingChild3

Known direct subclasses
BaseGridView

An abstract base class for vertically and horizontally scrolling lists.

WearableRecyclerView

Wearable specific implementation of the RecyclerView enabling setCircularScrollingGestureEnabled circular scrolling} and semi-circular layouts.

Known indirect subclasses
HorizontalGridView

A android.view.ViewGroup that shows items in a horizontal scrolling list.

VerticalGridView

A android.view.ViewGroup that shows items in a vertically scrolling list.


A flexible view for providing a limited window into a large data set.

Glossary of terms:

  • Adapter: A subclass of Adapter responsible for providing views that represent items in a data set.
  • Position: The position of a data item within an Adapter.
  • Index: The index of an attached child view as used in a call to getChildAt. Contrast with Position.
  • Binding: The process of preparing a child view to display data corresponding to a position within the adapter.
  • Recycle (view): A view previously used to display data for a specific adapter position may be placed in a cache for later reuse to display the same type of data again later. This can drastically improve performance by skipping initial layout inflation or construction.
  • Scrap (view): A child view that has entered into a temporarily detached state during layout. Scrap views may be reused without becoming fully detached from the parent RecyclerView, either unmodified if no rebinding is required or modified by the adapter if the view was considered dirty.
  • Dirty (view): A child view that must be rebound by the adapter before being displayed.

Positions in RecyclerView:

RecyclerView introduces an additional level of abstraction between the Adapter and LayoutManager to be able to detect data set changes in batches during a layout calculation. This saves LayoutManager from tracking adapter changes to calculate animations. It also helps with performance because all view bindings happen at the same time and unnecessary bindings are avoided.

For this reason, there are two types of position related methods in RecyclerView:

  • layout position: Position of an item in the latest layout calculation. This is the position from the LayoutManager's perspective.
  • adapter position: Position of an item in the adapter. This is the position from the Adapter's perspective.

These two positions are the same except the time between dispatching adapter.notify* events and calculating the updated layout.

Methods that return or receive *LayoutPosition* use position as of the latest layout calculation (e.g. getLayoutPosition, findViewHolderForLayoutPosition). These positions include all changes until the last layout calculation. You can rely on these positions to be consistent with what user is currently seeing on the screen. For example, if you have a list of items on the screen and user asks for the 5th element, you should use these methods as they'll match what user is seeing.

The other set of position related methods are in the form of *AdapterPosition*. (e.g. getAbsoluteAdapterPosition, getBindingAdapterPosition, findViewHolderForAdapterPosition) You should use these methods when you need to work with up-to-date adapter positions even if they may not have been reflected to layout yet. For example, if you want to access the item in the adapter on a ViewHolder click, you should use getBindingAdapterPosition. Beware that these methods may not be able to calculate adapter positions if notifyDataSetChanged has been called and new layout has not yet been calculated. For this reasons, you should carefully handle NO_POSITION or null results from these methods.

When writing a LayoutManager you almost always want to use layout positions whereas when writing an Adapter, you probably want to use adapter positions.

Presenting Dynamic Data

To display updatable data in a RecyclerView, your adapter needs to signal inserts, moves, and deletions to RecyclerView. You can build this yourself by manually calling adapter.notify* methods when content changes, or you can use one of the easier solutions RecyclerView provides: List diffing with DiffUtil If your RecyclerView is displaying a list that is re-fetched from scratch for each update (e.g. from the network, or from a database), DiffUtil can calculate the difference between versions of the list. DiffUtil takes both lists as input and computes the difference, which can be passed to RecyclerView to trigger minimal animations and updates to keep your UI performant, and animations meaningful. This approach requires that each list is represented in memory with immutable content, and relies on receiving updates as new instances of lists. This approach is also ideal if your UI layer doesn't implement sorting, it just presents the data in the order it's given.

The best part of this approach is that it extends to any arbitrary changes - item updates, moves, addition and removal can all be computed and handled the same way. Though you do have to keep two copies of the list in memory while diffing, and must avoid mutating them, it's possible to share unmodified elements between list versions.

There are three primary ways to do this for RecyclerView. We recommend you start with ListAdapter, the higher-level API that builds in List diffing on a background thread, with minimal code. AsyncListDiffer also provides this behavior, but without defining an Adapter to subclass. If you want more control, DiffUtil is the lower-level API you can use to compute the diffs yourself. Each approach allows you to specify how diffs should be computed based on item data.

List mutation with SortedList If your RecyclerView receives updates incrementally, e.g. item X is inserted, or item Y is removed, you can use SortedList to manage your list. You define how to order items, and it will automatically trigger update signals that RecyclerView can use. SortedList works if you only need to handle insert and remove events, and has the benefit that you only ever need to have a single copy of the list in memory. It can also compute differences with replaceAll, but this method is more limited than the list diffing behavior above. Paging Library The Paging library extends the diff-based approach to additionally support paged loading. It provides the androidx.paging.PagedList class that operates as a self-loading list, provided a source of data like a database, or paginated network API. It provides convenient list diffing support out of the box, similar to ListAdapter and AsyncListDiffer. For more information about the Paging library, see the library documentation. layoutManager

Summary

Nested types

public abstract class RecyclerView.Adapter<VH extends RecyclerView.ViewHolder>

Base class for an Adapter

Defines how this Adapter wants to restore its state after a view reconstruction (e.g. configuration change).

public abstract class RecyclerView.AdapterDataObserver

Observer base class for watching changes to an Adapter.

A callback interface that can be used to alter the drawing order of RecyclerView children.

EdgeEffectFactory lets you customize the over-scroll edge effect for RecyclerViews.

@Retention(value = RetentionPolicy.SOURCE)
@IntDef(value = )
public annotation RecyclerView.EdgeEffectFactory.EdgeDirection
public abstract class RecyclerView.ItemAnimator

This class defines the animations that take place on items as changes are made to the adapter.

@IntDef(flag = true, value = )
@Retention(value = RetentionPolicy.SOURCE)
public annotation RecyclerView.ItemAnimator.AdapterChanges

The set of flags that might be passed to recordPreLayoutInformation.

This interface is used to inform listeners when all pending or running animations in an ItemAnimator are finished.

A simple data structure that holds information about an item's bounds.

public abstract class RecyclerView.ItemDecoration

An ItemDecoration allows the application to add a special drawing and layout offset to specific item views from the adapter's data set.

public abstract class RecyclerView.LayoutManager

A LayoutManager is responsible for measuring and positioning item views within a RecyclerView as well as determining the policy for when to recycle item views that are no longer visible to the user.

Interface for LayoutManagers to request items to be prefetched, based on position, with specified distance from viewport, which indicates priority.

Some general properties that a LayoutManager may want to use.

LayoutParams subclass for children of RecyclerView.

A Listener interface that can be attached to a RecylcerView to get notified whenever a ViewHolder is attached to or detached from RecyclerView.

public abstract class RecyclerView.OnFlingListener

This class defines the behavior of fling if the developer wishes to handle it.

An OnItemTouchListener allows the application to intercept touch events in progress at the view hierarchy level of the RecyclerView before those touch events are considered for RecyclerView's own scrolling behavior.

public abstract class RecyclerView.OnScrollListener

An OnScrollListener can be added to a RecyclerView to receive messages when a scrolling event has occurred on that RecyclerView.

RecycledViewPool lets you share Views between multiple RecyclerViews.

public final inner class RecyclerView.Recycler

A Recycler is responsible for managing scrapped or detached item views for reuse.

A RecyclerListener can be set on a RecyclerView to receive messages whenever a view is recycled.

An implementation of RecyclerView.OnItemTouchListener that has empty method bodies and default return values.

public abstract class RecyclerView.SmoothScroller

Base class for smooth scrolling.

Holds information about a smooth scroll request by a SmoothScroller.

An interface which is optionally implemented by custom RecyclerView.LayoutManager to provide a hint to a SmoothScroller about the location of the target position.

public class RecyclerView.State

Contains useful information about the current RecyclerView state like target scroll position or view focus.

public abstract class RecyclerView.ViewCacheExtension

ViewCacheExtension is a helper class to provide an additional layer of view caching that can be controlled by the developer.

public abstract class RecyclerView.ViewHolder

A ViewHolder describes an item view and metadata about its place within the RecyclerView.

Constants

static final int
static final int
static final long
NO_ID = -1
static final int
static final int

The RecyclerView is currently being dragged by outside input such as user touch input.

static final int

The RecyclerView is not currently scrolling.

static final int

The RecyclerView is currently animating to a final position while not under outside control.

static final int

Constant for use with setScrollingTouchSlop.

static final int

Constant for use with setScrollingTouchSlop.

static final int
UNDEFINED_DURATION = -2147483648

Constant that represents that a duration has not been defined.

static final int

Public constructors

RecyclerView(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr
)

Public methods

void
addFocusables(ArrayList<View> views, int direction, int focusableMode)
void

Add an ItemDecoration to this RecyclerView.

void

Add an ItemDecoration to this RecyclerView.

void

Register a listener that will be notified whenever a child view is attached to or detached from RecyclerView.

void

Add an OnItemTouchListener to intercept touch events before they are dispatched to child views or this view's standard scrolling behavior.

void

Add a listener that will be notified of any changes in scroll state or position.

void

Register a listener that will be notified whenever a child view is recycled.

void

Removes all listeners that were added via addOnChildAttachStateChangeListener.

void

Remove all secondary listener that were notified of any changes in scroll state or position.

int

Compute the horizontal extent of the horizontal scrollbar's thumb within the horizontal range.

int

Compute the horizontal offset of the horizontal scrollbar's thumb within the horizontal range.

int

Compute the horizontal range that the horizontal scrollbar represents.

int

Compute the vertical extent of the vertical scrollbar's thumb within the vertical range.

int

Compute the vertical offset of the vertical scrollbar's thumb within the vertical range.

int

Compute the vertical range that the vertical scrollbar represents.

boolean
boolean
dispatchNestedFling(float velocityX, float velocityY, boolean consumed)
boolean
dispatchNestedPreFling(float velocityX, float velocityY)
boolean
dispatchNestedPreScroll(
    int dx,
    int dy,
    int[] consumed,
    int[] offsetInWindow
)
boolean
dispatchNestedPreScroll(
    int dx,
    int dy,
    int[] consumed,
    int[] offsetInWindow,
    int type
)

Dispatch one step of a nested scroll in progress before this view consumes any portion of it.

boolean
dispatchNestedScroll(
    int dxConsumed,
    int dyConsumed,
    int dxUnconsumed,
    int dyUnconsumed,
    int[] offsetInWindow
)
boolean
dispatchNestedScroll(
    int dxConsumed,
    int dyConsumed,
    int dxUnconsumed,
    int dyUnconsumed,
    int[] offsetInWindow,
    int type
)

Dispatch one step of a nested scroll in progress.

final void
dispatchNestedScroll(
    int dxConsumed,
    int dyConsumed,
    int dxUnconsumed,
    int dyUnconsumed,
    int[] offsetInWindow,
    int type,
    @NonNull int[] consumed
)

Dispatch one step of a nested scroll in progress.

boolean
void
boolean
drawChild(@NonNull Canvas canvas, View child, long drawingTime)
@Nullable View
findChildViewUnder(float x, float y)

Find the topmost view under the given point.

@Nullable View

Traverses the ancestors of the given view and returns the item view that contains it and also a direct child of the RecyclerView.

@Nullable RecyclerView.ViewHolder

Returns the ViewHolder that contains the given view.

@Nullable RecyclerView.ViewHolder

Return the ViewHolder for the item in the given position of the data set.

RecyclerView.ViewHolder

Return the ViewHolder for the item with the given id.

@Nullable RecyclerView.ViewHolder

Return the ViewHolder for the item in the given position of the data set as of the latest layout pass.

@Nullable RecyclerView.ViewHolder

This method is deprecated.

use findViewHolderForLayoutPosition or findViewHolderForAdapterPosition

boolean
fling(int velocityX, int velocityY)

Begin a standard fling with an initial velocity along each axis in pixels per second.

View
focusSearch(View focused, int direction)

Since RecyclerView is a collection ViewGroup that includes virtual children (items that are in the Adapter but not visible in the UI), it employs a more involved focus search strategy that differs from other ViewGroups.

ViewGroup.LayoutParams
CharSequence
@Nullable RecyclerView.Adapter

Retrieves the previously set adapter or null if no adapter is set.

int

Return the offset of the RecyclerView's text baseline from the its top boundary.

int

Return the adapter position that the given child view corresponds to.

long

Return the stable item id that the given child view corresponds to.

int

Return the adapter position of the given child view as of the latest completed layout pass.

int

This method is deprecated.

use getChildAdapterPosition or getChildLayoutPosition.

RecyclerView.ViewHolder

Retrieve the ViewHolder for the given child view.

boolean

Returns whether this RecyclerView will clip its children to its padding, and resize (but not clip) any EdgeEffect to the padded region, if padding is present.

@Nullable RecyclerViewAccessibilityDelegate

Returns the accessibility delegate compatibility implementation used by the RecyclerView.

void

Returns the bounds of the view including its decoration and margins.

@NonNull RecyclerView.EdgeEffectFactory

Retrieves the previously set EdgeEffectFactory or the default factory if nothing was set.

@Nullable RecyclerView.ItemAnimator

Gets the current ItemAnimator for this RecyclerView.

@NonNull RecyclerView.ItemDecoration

Returns an ItemDecoration previously added to this RecyclerView.

int

Returns the number of ItemDecoration currently added to this RecyclerView.

@Nullable RecyclerView.LayoutManager

Return the LayoutManager currently responsible for layout policy for this RecyclerView.

int

Returns the maximum fling velocity used by this RecyclerView.

int

Returns the minimum velocity to start a fling.

@Nullable RecyclerView.OnFlingListener

Get the current OnFlingListener from this RecyclerView.

boolean

Returns true if the RecyclerView should attempt to preserve currently focused Adapter Item's focus even if the View representing the Item is replaced during a layout calculation.

@NonNull RecyclerView.RecycledViewPool

Retrieve this RecyclerView's RecycledViewPool.

int

Return the current scrolling state of the RecyclerView.

boolean
boolean
boolean

Returns true if this view has a nested scrolling parent for the given input type.

boolean

Returns whether there are pending adapter updates which are not yet applied to the layout.

void

Invalidates all ItemDecorations.

boolean

Returns true if RecyclerView is currently running some animations.

boolean

Returns true if RecyclerView is attached to window.

boolean

Returns whether RecyclerView is currently computing a layout.

boolean

This method is deprecated.

Use isLayoutSuppressed.

final boolean

Returns whether layout and scroll calls on this container are currently being suppressed, due to an earlier call to suppressLayout.

boolean
void
nestedScrollBy(int x, int y)

Same as scrollBy, but also participates in nested scrolling.

void

Offset the bounds of all child views by dx pixels.

void

Offset the bounds of all child views by dy pixels.

void

Called when an item view is attached to this RecyclerView.

void

Called when an item view is detached from this RecyclerView.

void
boolean
boolean
void

Called when the scroll state of this RecyclerView changes.

void
onScrolled(@Px int dx, @Px int dy)

Called when the scroll position of this RecyclerView changes.

boolean
void

Remove an ItemDecoration from this RecyclerView.

void

Removes the ItemDecoration associated with the supplied index position.

void

Removes the provided listener from child attached state listeners list.

void

Remove an OnItemTouchListener.

void

Remove a listener that was notified of any changes in scroll state or position.

void

Removes the provided listener from RecyclerListener list.

void
requestChildFocus(View child, View focused)
boolean
requestChildRectangleOnScreen(View child, Rect rect, boolean immediate)
void
requestDisallowInterceptTouchEvent(boolean disallowIntercept)
void
void
scrollBy(int x, int y)
void
scrollTo(int x, int y)
void
scrollToPosition(int position)

Convenience method to scroll to a certain position.

void
void

Sets the accessibility delegate compatibility implementation used by RecyclerView.

void

Set a new adapter to provide child views on demand.

void

Sets the ChildDrawingOrderCallback to be used for drawing children.

void
setClipToPadding(boolean clipToPadding)
static void
setDebugAssertionsEnabled(boolean debugAssertionsEnabled)

Enable internal assertions about RecyclerView's state and throw exceptions if the assertions are violated.

void

Set a EdgeEffectFactory for this RecyclerView.

void
setHasFixedSize(boolean hasFixedSize)

RecyclerView can perform several optimizations if it can know in advance that RecyclerView's size is not affected by the adapter contents.

void

Sets the ItemAnimator that will handle animations involving changes to the items in this RecyclerView.

void

Set the number of offscreen views to retain before adding them to the potentially shared recycled view pool.

void
setLayoutFrozen(boolean frozen)

This method is deprecated.

Use suppressLayout.

void

Set the LayoutManager that this RecyclerView will use.

void

This method is deprecated.

Use setItemAnimator ()}.

void
setNestedScrollingEnabled(boolean enabled)
void

Set a OnFlingListener for this RecyclerView.

void

This method is deprecated.

Use addOnScrollListener and removeOnScrollListener

void
setPreserveFocusAfterLayout(boolean preserveFocusAfterLayout)

Set whether the RecyclerView should try to keep the same Item focused after a layout calculation or not.

void

Recycled view pools allow multiple RecyclerViews to share a common pool of scrap views.

void

This method is deprecated.

Use addRecyclerListener and removeRecyclerListener

void
setScrollingTouchSlop(int slopConstant)

Configure the scrolling touch slop for a specific use case.

static void
setVerboseLoggingEnabled(boolean verboseLoggingEnabled)

Enable verbose logging within RecyclerView itself.

void

Sets a new ViewCacheExtension to be used by the Recycler.

void
smoothScrollBy(@Px int dx, @Px int dy)

Animate a scroll by the given amount of pixels along either axis.

void
smoothScrollBy(@Px int dx, @Px int dy, @Nullable Interpolator interpolator)

Animate a scroll by the given amount of pixels along either axis.

void
smoothScrollBy(
    @Px int dx,
    @Px int dy,
    @Nullable Interpolator interpolator,
    int duration
)

Smooth scrolls the RecyclerView by a given distance.

void
smoothScrollToPosition(int position)

Starts a smooth scroll to an adapter position.

boolean
boolean
startNestedScroll(int axes, int type)

Begin a nestable scroll operation along the given axes, for the given input type.

void
void
stopNestedScroll(int type)

Stop a nested scroll in progress for the given input type.

void

Stop any current scroll in progress, such as one started by smoothScrollBy, fling or a touch-initiated fling.

final void
suppressLayout(boolean suppress)

Tells this RecyclerView to suppress all layout and scroll calls until layout suppression is disabled with a later call to suppressLayout(false).

void
swapAdapter(
    @Nullable RecyclerView.Adapter adapter,
    boolean removeAndRecycleExistingViews
)

Swaps the current adapter with the provided one.

Protected methods

boolean
void

Override to prevent thawing of any views created by the adapter.

void

Override to prevent freezing of any views created by the adapter.

ViewGroup.LayoutParams
ViewGroup.LayoutParams
int
getChildDrawingOrder(int childCount, int i)
void
void
void
onLayout(boolean changed, int l, int t, int r, int b)
void
onMeasure(int widthSpec, int heightSpec)
boolean
onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect)
void
Parcelable
void
onSizeChanged(int w, int h, int oldw, int oldh)
void
removeDetachedView(View child, boolean animate)

Inherited Constants

From android.view.View
static final int
static final int
static final int
static final int
static final int
static final int
static final Property<ViewFloat>
static final int
static final String
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE = "creditCardExpirationDate"
static final String
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY = "creditCardExpirationDay"
static final String
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH = "creditCardExpirationMonth"
static final String
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR = "creditCardExpirationYear"
static final String
static final String
AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE = "creditCardSecurityCode"
static final String
static final String
static final String
static final String
static final String
static final String
static final String
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int[]
static final int
static final int
static final int
static final int
static final int
static final int
static final int[]
static final int[]
static final int[]
static final int[]
static final int
static final int
static final int
static final int
static final int
static final int
static final int
GONE = 8
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
KEEP_SCREEN_ON = 67108864
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
static final int
NO_ID = -1
static final int
static final int
static final int
static final int[]
static final int[]