ViewPager2

public final class ViewPager2
extends ViewGroup

java.lang.Object
   ↳ android.view.View
     ↳ android.view.ViewGroup
       ↳ androidx.viewpager2.widget.ViewPager2


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

See also:

Summary

Nested classes

class ViewPager2.OnPageChangeCallback

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

interface ViewPager2.PageTransformer

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

Constants

int OFFSCREEN_PAGE_LIMIT_DEFAULT

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.

int ORIENTATION_HORIZONTAL

int ORIENTATION_VERTICAL

int SCROLL_STATE_DRAGGING

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

int SCROLL_STATE_IDLE

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

int SCROLL_STATE_SETTLING

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

Inherited constants

Inherited fields

Public constructors

ViewPager2(Context context)
ViewPager2(Context context, AttributeSet attrs)
ViewPager2(Context context, AttributeSet attrs, int defStyleAttr)
ViewPager2(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)

Public methods

void addItemDecoration(RecyclerView.ItemDecoration decor)

Add an RecyclerView.ItemDecoration to this ViewPager2.

void addItemDecoration(RecyclerView.ItemDecoration decor, int index)

Add an RecyclerView.ItemDecoration to this ViewPager2.

boolean beginFakeDrag()

Start a fake drag of the pager.

boolean endFakeDrag()

End a fake drag of the pager.

boolean fakeDragBy(float offsetPxFloat)

Fake drag by an offset in pixels.

CharSequence getAccessibilityClassName()
Adapter getAdapter()
int getCurrentItem()

Returns the currently selected page.

RecyclerView.ItemDecoration getItemDecorationAt(int index)

Returns an RecyclerView.ItemDecoration previously added to this ViewPager2.

int getItemDecorationCount()

Returns the number of RecyclerView.ItemDecoration currently added to this ViewPager2.

int getOffscreenPageLimit()

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 getOrientation()
int getScrollState()

Returns the current scroll state of the ViewPager2.

void invalidateItemDecorations()

Invalidates all ItemDecorations.

boolean isFakeDragging()

Returns true if a fake drag is in progress.

boolean isUserInputEnabled()

Returns if user initiated scrolling between pages is enabled.

void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info)
void onViewAdded(View child)
boolean performAccessibilityAction(int action, Bundle arguments)
void registerOnPageChangeCallback(ViewPager2.OnPageChangeCallback callback)

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

void removeItemDecoration(RecyclerView.ItemDecoration decor)

Remove an RecyclerView.ItemDecoration from this ViewPager2.

void removeItemDecorationAt(int index)

Removes the RecyclerView.ItemDecoration associated with the supplied index position.

void requestTransform()

Trigger a call to the registered PageTransformer's transformPage method.

void setAdapter(Adapter adapter)

Set a new adapter to provide page views on demand.

void setCurrentItem(int item)

Set the currently selected page.

void setCurrentItem(int item, boolean smoothScroll)

Set the currently selected page.

void setLayoutDirection(int layoutDirection)
void setOffscreenPageLimit(int limit)

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

void setOrientation(int orientation)

Sets the orientation of the ViewPager2.

void setPageTransformer(ViewPager2.PageTransformer transformer)

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

void setUserInputEnabled(boolean enabled)

Enable or disable user initiated scrolling.

void unregisterOnPageChangeCallback(ViewPager2.OnPageChangeCallback callback)

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

Protected methods

void dispatchRestoreInstanceState(SparseArray<Parcelable> container)
void onLayout(boolean changed, int l, int t, int r, int b)
void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
void onRestoreInstanceState(Parcelable state)
Parcelable onSaveInstanceState()

Inherited methods

Constants

OFFSCREEN_PAGE_LIMIT_DEFAULT

public static final int OFFSCREEN_PAGE_LIMIT_DEFAULT

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.

Constant Value: -1 (0xffffffff)

ORIENTATION_HORIZONTAL

public static final int ORIENTATION_HORIZONTAL

Constant Value: 0 (0x00000000)

ORIENTATION_VERTICAL

public static final int ORIENTATION_VERTICAL

Constant Value: 1 (0x00000001)

SCROLL_STATE_DRAGGING

public static final int SCROLL_STATE_DRAGGING

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

Constant Value: 1 (0x00000001)

SCROLL_STATE_IDLE

public static final int SCROLL_STATE_IDLE

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

Constant Value: 0 (0x00000000)

SCROLL_STATE_SETTLING

public static final int SCROLL_STATE_SETTLING

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

Constant Value: 2 (0x00000002)

Public constructors

ViewPager2

public ViewPager2 (Context context)

Parameters
context Context

ViewPager2

public ViewPager2 (Context context, 
                AttributeSet attrs)

Parameters
context Context

attrs AttributeSet

ViewPager2

public ViewPager2 (Context context, 
                AttributeSet attrs, 
                int defStyleAttr)

Parameters
context Context

attrs AttributeSet

defStyleAttr int

ViewPager2

public ViewPager2 (Context context, 
                AttributeSet attrs, 
                int defStyleAttr, 
                int defStyleRes)

Parameters
context Context

attrs AttributeSet

defStyleAttr int

defStyleRes int

Public methods

addItemDecoration

public void addItemDecoration (RecyclerView.ItemDecoration decor)

Add an RecyclerView.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

public void addItemDecoration (RecyclerView.ItemDecoration decor, 
                int index)

Add an RecyclerView.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 int: Position in the decoration chain to insert this decoration at. If this value is negative the decoration will be added at the end.

Throws
IndexOutOfBoundsException on indexes larger than getItemDecorationCount()

beginFakeDrag

public boolean beginFakeDrag ()

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.

Returns
boolean true if the fake drag began successfully, false if it could not be started

endFakeDrag

public boolean endFakeDrag ()

End a fake drag of the pager.

Returns
boolean true if the fake drag was ended. If false is returned, it means there was no fake drag to end.

fakeDragBy

public boolean fakeDragBy (float offsetPxFloat)

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

Returns
boolean true if the fake drag was executed. If false is returned, it means there was no fake drag to end.

getAccessibilityClassName

public CharSequence getAccessibilityClassName ()

Returns
CharSequence

getAdapter

public Adapter getAdapter ()

Returns
Adapter

getCurrentItem

public int getCurrentItem ()

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

Returns
int Currently selected page

getItemDecorationAt

public RecyclerView.ItemDecoration getItemDecorationAt (int index)

Returns an RecyclerView.ItemDecoration previously added to this ViewPager2.

Parameters
index int: The index position of the desired ItemDecoration.

Returns
RecyclerView.ItemDecoration the ItemDecoration at index position

Throws
IndexOutOfBoundsException on invalid index

getItemDecorationCount

public int getItemDecorationCount ()

Returns the number of RecyclerView.ItemDecoration currently added to this ViewPager2.

Returns
int number of ItemDecorations currently added added to this ViewPager2.

getOffscreenPageLimit

public int getOffscreenPageLimit ()

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.

Returns
int How many pages will be kept offscreen on either side

getOrientation

public int getOrientation ()

Returns
int

getScrollState

public int getScrollState ()

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.

Returns
int The scroll state that was last dispatched to ViewPager2.OnPageChangeCallback.onPageScrollStateChanged(int)

invalidateItemDecorations

public void invalidateItemDecorations ()

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

isFakeDragging

public boolean isFakeDragging ()

Returns true if a fake drag is in progress.

Returns
boolean true if currently in a fake drag, false otherwise.

isUserInputEnabled

public boolean isUserInputEnabled ()

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

Returns
boolean true if users can scroll the ViewPager2, false otherwise

onInitializeAccessibilityNodeInfo

public void onInitializeAccessibilityNodeInfo (AccessibilityNodeInfo info)

Parameters
info AccessibilityNodeInfo

onViewAdded

public void onViewAdded (View child)

Parameters
child View

performAccessibilityAction

public boolean performAccessibilityAction (int action, 
                Bundle arguments)

Parameters
action int

arguments Bundle

Returns
boolean

registerOnPageChangeCallback

public void registerOnPageChangeCallback (ViewPager2.OnPageChangeCallback callback)

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

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

Parameters
callback ViewPager2.OnPageChangeCallback: callback to add

removeItemDecoration

public void removeItemDecoration (RecyclerView.ItemDecoration decor)

Remove an RecyclerView.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

public void removeItemDecorationAt (int index)

Removes the RecyclerView.ItemDecoration associated with the supplied index position.

Parameters
index int: The index position of the ItemDecoration to be removed.

Throws
IndexOutOfBoundsException on invalid index

requestTransform

public void requestTransform ()

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

setAdapter

public void setAdapter (Adapter adapter)

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 getLayoutTransition().setAnimateParentHierarchy(false) 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 Adapter: The adapter to use, or null to remove the current adapter

setCurrentItem

public void setCurrentItem (int item)

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

public void setCurrentItem (int item, 
                boolean smoothScroll)

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 boolean: True to smoothly scroll to the new item, false to transition immediately

setLayoutDirection

public void setLayoutDirection (int layoutDirection)

Parameters
layoutDirection int

setOffscreenPageLimit

public void setOffscreenPageLimit (int limit)

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

Throws
IllegalArgumentException If the given limit is invalid

setOrientation

public void setOrientation (int orientation)

Sets the orientation of the ViewPager2.

Parameters
orientation int: ORIENTATION_HORIZONTAL or ORIENTATION_VERTICAL

setPageTransformer

public void setPageTransformer (ViewPager2.PageTransformer transformer)

Sets a ViewPager2.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 ViewPager2.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

public void setUserInputEnabled (boolean enabled)

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

public void unregisterOnPageChangeCallback (ViewPager2.OnPageChangeCallback callback)

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

Parameters
callback ViewPager2.OnPageChangeCallback: callback to remove

Protected methods

dispatchRestoreInstanceState

protected void dispatchRestoreInstanceState (SparseArray<Parcelable> container)

Parameters
container SparseArray

onLayout

protected void onLayout (boolean changed, 
                int l, 
                int t, 
                int r, 
                int b)

Parameters
changed boolean

l int

t int

r int

b int

onMeasure

protected void onMeasure (int widthMeasureSpec, 
                int heightMeasureSpec)

Parameters
widthMeasureSpec int

heightMeasureSpec int

onRestoreInstanceState

protected void onRestoreInstanceState (Parcelable state)

Parameters
state Parcelable

onSaveInstanceState

protected Parcelable onSaveInstanceState ()

Returns
Parcelable