ViewPager2

class ViewPager2 : ViewGroup
kotlin.Any
   ↳ android.view.View
   ↳ android.view.ViewGroup
   ↳ androidx.viewpager2.widget.ViewPager2

ViewPager2 replaces androidx.viewpager.widget.ViewPager, addressing most of its predecessor’s pain-points, including right-to-left layout support, vertical orientation, modifiable Fragment collections, etc.

Summary

Nested classes

abstract

Callback interface for responding to changing state of the selected page.

abstract

A PageTransformer is invoked whenever a visible/attached page is scrolled.

Constants

static Int

Value to indicate that the default caching mechanism of RecyclerView should be used instead of explicitly prefetch and retain pages to either side of the current page.

static Int

static Int

static Int

Indicates that the ViewPager2 is currently being dragged by the user, or programmatically via fake drag functionality.

static Int

Indicates that the ViewPager2 is in an idle, settled state.

static Int

Indicates that the ViewPager2 is in the process of settling to a final position.

Public constructors

<init>(@NonNull context: Context)

<init>(@NonNull context: Context, @Nullable attrs: AttributeSet?)

<init>(@NonNull context: Context, @Nullable attrs: AttributeSet?, defStyleAttr: Int)

<init>(@NonNull context: Context, @Nullable attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int)

Public methods

Unit

Add an ItemDecoration to this ViewPager2.

Unit

Add an ItemDecoration to this ViewPager2.

Boolean

Start a fake drag of the pager.

Boolean

End a fake drag of the pager.

Boolean
fakeDragBy(@Px offsetPxFloat: Float)

Fake drag by an offset in pixels.

CharSequence!

RecyclerView.Adapter<RecyclerView.ViewHolder!>?

Int

Returns the currently selected page.

RecyclerView.ItemDecoration

Returns an ItemDecoration previously added to this ViewPager2.

Int

Returns the number of ItemDecoration currently added to this ViewPager2.

Int

Returns the number of pages that will be retained to either side of the current page in the view hierarchy in an idle state.

Int

Int

Returns the current scroll state of the ViewPager2.

Unit

Invalidates all ItemDecorations.

Boolean

Returns true if a fake drag is in progress.

Boolean

Returns if user initiated scrolling between pages is enabled.

Unit

Unit
onViewAdded(child: View!)

Boolean
performAccessibilityAction(action: Int, arguments: Bundle!)

Unit

Add a callback that will be invoked whenever the page changes or is incrementally scrolled.

Unit

Remove an ItemDecoration from this ViewPager2.

Unit

Removes the ItemDecoration associated with the supplied index position.

Unit

Trigger a call to the registered PageTransformer's method.

Unit

Set a new adapter to provide page views on demand.

Unit

Set the currently selected page.

Unit
setCurrentItem(item: Int, smoothScroll: Boolean)

Set the currently selected page.

Unit
setLayoutDirection(layoutDirection: Int)

Unit

Set the number of pages that should be retained to either side of the currently visible page(s).

Unit
setOrientation(orientation: Int)

Sets the orientation of the ViewPager2.

Unit

Sets a PageTransformer that will be called for each attached page whenever the scroll position is changed.

Unit

Enable or disable user initiated scrolling.

Unit

Remove a callback that was previously added via registerOnPageChangeCallback(OnPageChangeCallback).

Protected methods

Unit

Unit
onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int)

Unit
onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int)

Unit

Parcelable?

Constants

OFFSCREEN_PAGE_LIMIT_DEFAULT

static val OFFSCREEN_PAGE_LIMIT_DEFAULT: Int

Value to indicate that the default caching mechanism of RecyclerView should be used instead of explicitly prefetch and retain pages to either side of the current page.

Value: -1

ORIENTATION_HORIZONTAL

static val ORIENTATION_HORIZONTAL: Int
Value: RecyclerView.HORIZONTAL

ORIENTATION_VERTICAL

static val ORIENTATION_VERTICAL: Int
Value: RecyclerView.VERTICAL

SCROLL_STATE_DRAGGING

static val SCROLL_STATE_DRAGGING: Int

Indicates that the ViewPager2 is currently being dragged by the user, or programmatically via fake drag functionality.

Value: 1

SCROLL_STATE_IDLE

static val SCROLL_STATE_IDLE: Int

Indicates that the ViewPager2 is in an idle, settled state. The current page is fully in view and no animation is in progress.

Value: 0

SCROLL_STATE_SETTLING

static val SCROLL_STATE_SETTLING: Int

Indicates that the ViewPager2 is in the process of settling to a final position.

Value: 2

Public constructors

<init>

ViewPager2(@NonNull context: Context)

<init>

ViewPager2(@NonNull context: Context, @Nullable attrs: AttributeSet?)

<init>

ViewPager2(@NonNull context: Context, @Nullable attrs: AttributeSet?, defStyleAttr: Int)

<init>

ViewPager2(@NonNull context: Context, @Nullable attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int)

Public methods

addItemDecoration

fun addItemDecoration(@NonNull decor: RecyclerView.ItemDecoration): Unit

Add an ItemDecoration to this ViewPager2. Item decorations can affect both measurement and drawing of individual item views.

Item decorations are ordered. Decorations placed earlier in the list will be run/queried/drawn first for their effects on item views. Padding added to views will be nested; a padding added by an earlier decoration will mean further item decorations in the list will be asked to draw/pad within the previous decoration's given area.

Parameters
decor RecyclerView.ItemDecoration: Decoration to add

addItemDecoration

fun addItemDecoration(@NonNull decor: RecyclerView.ItemDecoration, index: Int): Unit

Add an ItemDecoration to this ViewPager2. Item decorations can affect both measurement and drawing of individual item views.

Item decorations are ordered. Decorations placed earlier in the list will be run/queried/drawn first for their effects on item views. Padding added to views will be nested; a padding added by an earlier decoration will mean further item decorations in the list will be asked to draw/pad within the previous decoration's given area.

Parameters
decor RecyclerView.ItemDecoration: Decoration to add
index RecyclerView.ItemDecoration: Position in the decoration chain to insert this decoration at. If this value is negative the decoration will be added at the end.
Exceptions
IndexOutOfBoundsException on indexes larger than getItemDecorationCount

beginFakeDrag

fun beginFakeDrag(): Boolean

Start a fake drag of the pager.

A fake drag can be useful if you want to synchronize the motion of the ViewPager2 with the touch scrolling of another view, while still letting the ViewPager2 control the snapping motion and fling behavior. (e.g. parallax-scrolling tabs.) Call fakeDragBy(float) to simulate the actual drag motion. Call endFakeDrag() to complete the fake drag and fling as necessary.

A fake drag can be interrupted by a real drag. From that point on, all calls to fakeDragBy and endFakeDrag will be ignored until the next fake drag is started by calling beginFakeDrag. If you need the ViewPager2 to ignore touch events and other user input during a fake drag, use setUserInputEnabled(boolean). If a real or fake drag is already in progress, this method will return false.

Return
Boolean: true if the fake drag began successfully, false if it could not be started

endFakeDrag

fun endFakeDrag(): Boolean

End a fake drag of the pager.

Return
Boolean: true if the fake drag was ended. If false is returned, it means there was no fake drag to end.

fakeDragBy

fun fakeDragBy(@Px offsetPxFloat: Float): Boolean

Fake drag by an offset in pixels. You must have called beginFakeDrag() first. Drag happens in the direction of the orientation. Positive offsets will drag to the previous page, negative values to the next page, with one exception: if layout direction is set to RTL and the ViewPager2's orientation is horizontal, then the behavior will be inverted. This matches the deltas of touch events that would cause the same real drag.

If the pager is not in the fake dragging state anymore, it ignores this call and returns false.

Parameters
offsetPxFloat Float: Offset in pixels to drag by
Return
Boolean: true if the fake drag was executed. If false is returned, it means there was no fake drag to end.

getAccessibilityClassName

fun getAccessibilityClassName(): CharSequence!

getAdapter

@Nullable fun getAdapter(): RecyclerView.Adapter<RecyclerView.ViewHolder!>?

getCurrentItem

fun getCurrentItem(): Int

Returns the currently selected page. If no page can sensibly be selected because there is no adapter or the adapter is empty, returns 0.

Return
Int: Currently selected page

getItemDecorationAt

@NonNull fun getItemDecorationAt(index: Int): RecyclerView.ItemDecoration

Returns an ItemDecoration previously added to this ViewPager2.

Parameters
index Int: The index position of the desired ItemDecoration.
Return
RecyclerView.ItemDecoration: the ItemDecoration at index position
Exceptions
IndexOutOfBoundsException on invalid index

getItemDecorationCount

fun getItemDecorationCount(): Int

Returns the number of ItemDecoration currently added to this ViewPager2.

Return
Int: number of ItemDecorations currently added added to this ViewPager2.

getOffscreenPageLimit

fun getOffscreenPageLimit(): Int

Returns the number of pages that will be retained to either side of the current page in the view hierarchy in an idle state. Defaults to OFFSCREEN_PAGE_LIMIT_DEFAULT.

Return
Int: How many pages will be kept offscreen on either side

getOrientation

fun getOrientation(): Int

getScrollState

fun getScrollState(): Int

Returns the current scroll state of the ViewPager2. Returned value is one of can be one of SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING or SCROLL_STATE_SETTLING.

Return
Int: The scroll state that was last dispatched to

invalidateItemDecorations

fun invalidateItemDecorations(): Unit

Invalidates all ItemDecorations. If ViewPager2 has item decorations, calling this method will trigger a requestLayout() call.

isFakeDragging

fun isFakeDragging(): Boolean

Returns true if a fake drag is in progress.

Return
Boolean: true if currently in a fake drag, false otherwise.

isUserInputEnabled

fun isUserInputEnabled(): Boolean

Returns if user initiated scrolling between pages is enabled. Enabled by default.

Return
Boolean: true if users can scroll the ViewPager2, false otherwise

onInitializeAccessibilityNodeInfo

fun onInitializeAccessibilityNodeInfo(info: AccessibilityNodeInfo!): Unit

onViewAdded

fun onViewAdded(child: View!): Unit

performAccessibilityAction

fun performAccessibilityAction(action: Int, arguments: Bundle!): Boolean

registerOnPageChangeCallback

fun registerOnPageChangeCallback(@NonNull callback: ViewPager2.OnPageChangeCallback): Unit

Add a callback that will be invoked whenever the page changes or is incrementally scrolled. See OnPageChangeCallback.

Components that add a callback should take care to remove it when finished.

Parameters
callback ViewPager2.OnPageChangeCallback: callback to add

removeItemDecoration

fun removeItemDecoration(@NonNull decor: RecyclerView.ItemDecoration): Unit

Remove an ItemDecoration from this ViewPager2.

The given decoration will no longer impact the measurement and drawing of item views.

Parameters
decor RecyclerView.ItemDecoration: Decoration to remove

removeItemDecorationAt

fun removeItemDecorationAt(index: Int): Unit

Removes the ItemDecoration associated with the supplied index position.

Parameters
index Int: The index position of the ItemDecoration to be removed.
Exceptions
IndexOutOfBoundsException on invalid index

requestTransform

fun requestTransform(): Unit

Trigger a call to the registered PageTransformer's method. Call this when something has changed which has invalidated the transformations defined by the PageTransformer that did not trigger a page scroll.

setAdapter

fun setAdapter(@Nullable adapter: RecyclerView.Adapter<RecyclerView.ViewHolder!>?): Unit

Set a new adapter to provide page views on demand.

If you're planning to use Fragments as pages, implement FragmentStateAdapter. If your pages are Views, implement RecyclerView.Adapter as usual.

If your pages contain LayoutTransitions, then those LayoutTransitions must have animateParentHierarchy set to false. Note that if you have a ViewGroup with animateLayoutChanges="true" in your layout xml file, a LayoutTransition is added automatically to that ViewGroup. You will need to manually call on that ViewGroup after you inflated the xml layout, like this:

View view = layoutInflater.inflate(R.layout.page, parent, false);
      ViewGroup viewGroup = view.findViewById(R.id.animated_viewgroup);
      viewGroup.getLayoutTransition().setAnimateParentHierarchy(false);
      
Parameters
adapter RecyclerView.Adapter<RecyclerView.ViewHolder!>?: The adapter to use, or null to remove the current adapter

setCurrentItem

fun setCurrentItem(item: Int): Unit

Set the currently selected page. If the ViewPager has already been through its first layout with its current adapter there will be a smooth animated transition between the current item and the specified item. Silently ignored if the adapter is not set or empty. Clamps item to the bounds of the adapter. TODO(b/123069219): verify first layout behavior

Parameters
item Int: Item index to select

setCurrentItem

fun setCurrentItem(item: Int, smoothScroll: Boolean): Unit

Set the currently selected page. If smoothScroll = true, will perform a smooth animation from the current item to the new item. Silently ignored if the adapter is not set or empty. Clamps item to the bounds of the adapter.

Parameters
item Int: Item index to select
smoothScroll Int: True to smoothly scroll to the new item, false to transition immediately

setLayoutDirection

fun setLayoutDirection(layoutDirection: Int): Unit

setOffscreenPageLimit

fun setOffscreenPageLimit(limit: Int): Unit

Set the number of pages that should be retained to either side of the currently visible page(s). Pages beyond this limit will be recreated from the adapter when needed. Set this to OFFSCREEN_PAGE_LIMIT_DEFAULT to use RecyclerView's caching strategy. The given value must either be larger than 0, or OFFSCREEN_PAGE_LIMIT_DEFAULT.

Pages within limit pages away from the current page are created and added to the view hierarchy, even though they are not visible on the screen. Pages outside this limit will be removed from the view hierarchy, but the ViewHolders will be recycled as usual by RecyclerView.

This is offered as an optimization. If you know in advance the number of pages you will need to support or have lazy-loading mechanisms in place on your pages, tweaking this setting can have benefits in perceived smoothness of paging animations and interaction. If you have a small number of pages (3-4) that you can keep active all at once, less time will be spent in layout for newly created view subtrees as the user pages back and forth.

You should keep this limit low, especially if your pages have complex layouts. By default it is set to OFFSCREEN_PAGE_LIMIT_DEFAULT.

Parameters
limit Int: How many pages will be kept offscreen on either side. Valid values are all values >= 1 and OFFSCREEN_PAGE_LIMIT_DEFAULT
Exceptions
IllegalArgumentException If the given limit is invalid

setOrientation

fun setOrientation(orientation: Int): Unit

Sets the orientation of the ViewPager2.

Parameters
orientation Int: ORIENTATION_HORIZONTAL or ORIENTATION_VERTICAL

setPageTransformer

fun setPageTransformer(@Nullable transformer: ViewPager2.PageTransformer?): Unit

Sets a PageTransformer that will be called for each attached page whenever the scroll position is changed. This allows the application to apply custom property transformations to each page, overriding the default sliding behavior.

Note: setting a PageTransformer disables data-set change animations to prevent conflicts between the two animation systems. Setting a null transformer will restore data-set change animations.

Parameters
transformer ViewPager2.PageTransformer?: PageTransformer that will modify each page's animation properties

setUserInputEnabled

fun setUserInputEnabled(enabled: Boolean): Unit

Enable or disable user initiated scrolling. This includes touch input (scroll and fling gestures) and accessibility input. Disabling keyboard input is not yet supported. When user initiated scrolling is disabled, programmatic scrolls through setCurrentItem still work. By default, user initiated scrolling is enabled.

Parameters
enabled Boolean: true to allow user initiated scrolling, false to block user initiated scrolling

unregisterOnPageChangeCallback

fun unregisterOnPageChangeCallback(@NonNull callback: ViewPager2.OnPageChangeCallback): Unit

Remove a callback that was previously added via registerOnPageChangeCallback(OnPageChangeCallback).

Parameters
callback ViewPager2.OnPageChangeCallback: callback to remove

Protected methods

dispatchRestoreInstanceState

protected fun dispatchRestoreInstanceState(container: SparseArray<Parcelable!>!): Unit

onLayout

protected fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int): Unit

onMeasure

protected fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int): Unit

onRestoreInstanceState

protected fun onRestoreInstanceState(state: Parcelable!): Unit

onSaveInstanceState

@Nullable protected fun onSaveInstanceState(): Parcelable?