ViewPager2


public final class ViewPager2 extends ViewGroup


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.

A note on WindowInsets: due to a bug in API 29 and before, WindowInsets were incorrectly dispatched to a View's children and siblings. ViewPager2 offers a fix to make sure that all pages receive the correct insets, but it comes at the cost of not dispatching insets to any siblings of ViewPager2 or siblings of its ancestors that haven't received the insets yet. If you want to handle insets on each page separately (instead of on ViewPager2 or one of its parents), you should install a WindowInsetsApplier by calling WindowInsetsApplier.install(viewPager2). If you don't handle insets on any of the pages, we recommend you don't use the WindowInsetsApplier.

See also
ViewPager

Summary

Nested types

public abstract class ViewPager2.OnPageChangeCallback

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

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

Constants

static final 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 final int
static final int
static final int

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

static final int

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

static final int

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

Public constructors

ViewPager2(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr
)
@RequiresApi(value = 21)
ViewPager2(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr,
    int defStyleRes
)

Public methods

void

Add an ItemDecoration to this ViewPager2.

void

Add an ItemDecoration to this ViewPager2.

boolean

Start a fake drag of the pager.

boolean
canScrollHorizontally(int direction)
boolean
canScrollVertically(int direction)
boolean

End a fake drag of the pager.

boolean
fakeDragBy(@Px float offsetPxFloat)

Fake drag by an offset in pixels.

CharSequence
@Nullable RecyclerView.Adapter
int

Returns the currently selected page.

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

void

Invalidates all ItemDecorations.

boolean

Returns true if a fake drag is in progress.

boolean

Returns if user initiated scrolling between pages is enabled.

void
void
boolean
performAccessibilityAction(int action, @Nullable Bundle arguments)
void

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

void

Remove an ItemDecoration from this ViewPager2.

void

Removes the ItemDecoration associated with the supplied index position.

void

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

void

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

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

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

Remove a callback that was previously added via registerOnPageChangeCallback.

Protected methods

void
void
onLayout(boolean changed, int l, int t, int r, int b)
void
onMeasure(int widthMeasureSpec, int heightMeasureSpec)
void
@Nullable Parcelable

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[]
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 Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
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

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

static final int

This field is deprecated.

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 Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
static final String
VIEW_LOG_TAG = "View"
static final int
static final int[]
static final Property<ViewFloat>
static final Property<ViewFloat>
static final Property<ViewFloat>
From android.view.ViewGroup
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

This field is deprecated.

Inherited methods

From android.view.View
void
void
void
ViewPropertyAnimator
void
void
boolean
void
void

This method is deprecated.

void
boolean
boolean
boolean
boolean
final void
void
final void
boolean
void
void
static int
combineMeasuredStates(int curState, int newState)
int
int
int
void
WindowInsets
int
int
int
AccessibilityNodeInfo
void
void

This method is deprecated.

boolean
boolean
dispatchNestedFling(float velocityX, float velocityY, boolean consumed)
boolean
dispatchNestedPreFling(float velocityX, float velocityY)
boolean
dispatchNestedPrePerformAccessibilityAction(
    int action,
    Bundle arguments
)
boolean
dispatchNestedPreScroll(
    int dx,
    int dy,
    int[] consumed,
    int[] offsetInWindow
)
boolean
dispatchNestedScroll(
    int dxConsumed,
    int dyConsumed,
    int dxUnconsumed,
    int dyUnconsumed,
    int[] offsetInWindow
)
boolean
void
draw(Canvas canvas)
void
drawableHotspotChanged(float x, float y)
final OnBackInvokedDispatcher
final T
<T extends View> findViewById(int id)
final T
<T extends View> findViewWithTag(Object tag)
boolean

This method is deprecated.

void
forceHasOverlappingRendering(boolean hasOverlappingRendering)
void
void
generateDisplayHash(
    String hashAlgorithm,
    Rect bounds,
    Executor executor,
    DisplayHashResultCallback callback
)
static int
View.AccessibilityDelegate
int
AccessibilityNodeProvider
CharSequence
int
int
String
String
float
Animation
Matrix
IBinder
int[]
Map<IntegerInteger>
String[]
final AutofillId
int
AutofillValue
Drawable
BlendMode
ColorStateList
PorterDuff.Mode
int
final int
float
int
float
Rect
boolean
final boolean
final ContentCaptureSession
CharSequence
final Context
ContextMenu.ContextMenuInfo
final boolean
static int
getDefaultSize(int size, int measureSpec)
Display
final int[]
Bitmap

This method is deprecated.

int

This method is deprecated.

int

This method is deprecated.

void
long
float
int
boolean
boolean
int
ArrayList<View>
getFocusables(int direction)
void
Drawable
int
BlendMode
ColorStateList
PorterDuff.Mode
boolean
getGlobalVisibleRect(Rect r, Point globalOffset)
Handler
float
float
float
float
Runnable
final boolean
final int
void
getHitRect(Rect outRect)
int
int
Drawable
Drawable
int
int
int
int
boolean
KeyEvent.DispatcherState
int
int
int
ViewGroup.LayoutParams
final int
float
int
final boolean
void
getLocationInSurface(int[] location)
void
getLocationInWindow(int[] outLocation)
void
getLocationOnScreen(int[] outLocation)
Matrix
final int
final int
final int
final int
final int
int
int
int
int
int
int
int
int
View.OnFocusChangeListener
int
ViewOutlineProvider
int
int
ViewOverlay
int
int
int
int
int
int
final ViewParent
ViewParent
float
float
PointerIcon
final List<Rect>
String[]
Resources
final boolean
final int
float
int
AttachedSurfaceControl
View
WindowInsets
float
float
float
float
float
int
int
int
int
int
int
final int
final int
int
int
final CharSequence
StateListAnimator
int
int
List<Rect>
int

This method is deprecated.

Object
int
int
CharSequence
final int
float
int
TouchDelegate
ArrayList<View>
float
String
float
float
float
long
int
int
Drawable
Drawable
int
ViewTranslationResponse
ViewTreeObserver
int
final int
int
WindowId
WindowInsetsController
int

This method is deprecated.

IBinder
int
void
float
float
float
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
static View
inflate(Context context, int resource, ViewGroup root)
void

This method is deprecated.

void
void
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean

This method is deprecated.

boolean
boolean
final boolean
final boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
final boolean
final boolean
boolean
boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
final boolean
boolean
boolean
final boolean
boolean
boolean
boolean
boolean
boolean
View
keyboardNavigationClusterSearch(View currentCluster, int direction)
final void
measure(int widthMeasureSpec, int heightMeasureSpec)
static int[]
mergeDrawableStates(int[] baseState, int[] additionalState)
void
offsetLeftAndRight(int offset)
void
offsetTopAndBottom(int offset)
void
void
WindowInsets
void
boolean
boolean
void
void
InputConnection
void
onCreateViewTranslationRequest(
    int[] supportedFormats,
    Consumer<ViewTranslationRequest> requestsCollector
)
void
onCreateVirtualViewTranslationRequests(
    long[] virtualIds,
    int[] supportedFormats,
    Consumer<ViewTranslationRequest> requestsCollector
)
void
onDisplayHint(int hint)
boolean
void
onDraw(Canvas canvas)
void
final void
boolean
void
void
void
onFocusChanged(
    boolean gainFocus,
    int direction,
    Rect previouslyFocusedRect
)
boolean
void
onHoverChanged(boolean hovered)
boolean
void
boolean
onKeyDown(int keyCode, KeyEvent event)
boolean
onKeyLongPress(int keyCode, KeyEvent event)
boolean
onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
boolean
onKeyPreIme(int keyCode, KeyEvent event)
boolean
onKeyShortcut(int keyCode, KeyEvent event)
boolean
onKeyUp(int keyCode, KeyEvent event)
void
onOverScrolled(
    int scrollX,
    int scrollY,
    boolean clampedX,
    boolean clampedY
)
void
onPointerCaptureChange(boolean hasCapture)
void
void
onProvideAutofillStructure(ViewStructure structure, int flags)
void
void
void
void
ContentInfo
void
onRtlPropertiesChanged(int layoutDirection)
void
onScreenStateChanged(int screenState)
void
onScrollCaptureSearch(
    Rect localVisibleRect,
    Point windowOffset,
    Consumer<ScrollCaptureTarget> targets
)
void
onScrollChanged(int l, int t, int oldl, int oldt)
boolean
onSetAlpha(int alpha)
void
onSizeChanged(int w, int h, int oldw, int oldh)
void
boolean
boolean
void
void
void
onVisibilityAggregated(boolean isVisible)
void
onVisibilityChanged(View changedView, int visibility)
void
onWindowFocusChanged(boolean hasWindowFocus)
void

This method is deprecated.

void
onWindowVisibilityChanged(int visibility)
boolean
overScrollBy(
    int deltaX,
    int deltaY,
    int scrollX,
    int scrollY,
    int scrollRangeX,
    int scrollRangeY,
    int maxOverScrollX,
    int maxOverScrollY,
    boolean isTouchEvent
)
boolean
boolean
performContextClick(float x, float y)
boolean
performHapticFeedback(int feedbackConstant)
boolean
ContentInfo
void
playSoundEffect(int soundConstant)
boolean
post(Runnable action)
boolean
postDelayed(Runnable action, long delayMillis)
void
void
postInvalidateDelayed(long delayMilliseconds)
void
void
void
postOnAnimationDelayed(Runnable action, long delayMillis)
void
void
boolean
void
void
void
void
void

This method is deprecated.

final boolean
void
void
boolean
final void
final T
<T extends View> requireViewById(int id)
void
static int
resolveSize(int size, int measureSpec)
static int
resolveSizeAndState(int size, int measureSpec, int childMeasuredState)
void
final void
saveAttributeDataForStyleable(
    Context context,
    int[] styleable,
    AttributeSet attrs,
    TypedArray t,
    int defStyleAttr,
    int defStyleRes
)
void
void
scheduleDrawable(Drawable who, Runnable what, long when)
void
scrollBy(int x, int y)
void
scrollTo(int x, int y)
void
sendAccessibilityEvent(int eventType)
void
void
setAccessibilityDataSensitive(int accessibilityDataSensitive)
void
void
setAccessibilityHeading(boolean isHeading)
void
void
setAccessibilityPaneTitle(CharSequence accessibilityPaneTitle)
void
void
void
setActivated(boolean activated)
void
setAllowClickWhenDisabled(boolean clickableWhenDisabled)
void
void
void
setAlpha(float alpha)
void
void
void
setAutoHandwritingEnabled(boolean enabled)
void
setAutofillHints(String[] autofillHints)
void
void
setBackground(Drawable background)
void
setBackgroundColor(int color)
void

This method is deprecated.

void
void
void
void
final void
setBottom(int bottom)
void
setCameraDistance(float distance)
void
setClickable(boolean clickable)
void
setClipBounds(Rect clipBounds)
void
setClipToOutline(boolean clipToOutline)
void
void
setContentDescription(CharSequence contentDescription)
void
setContextClickable(boolean contextClickable)
void
setDefaultFocusHighlightEnabled(boolean defaultFocusHighlightEnabled)
void

This method is deprecated.

void
setDrawingCacheEnabled(boolean enabled)

This method is deprecated.

void

This method is deprecated.

void
void
setElevation(float elevation)
void
setEnabled(boolean enabled)
void
setFadingEdgeLength(int length)
void
void
setFitsSystemWindows(boolean fitSystemWindows)
void
setFocusable(boolean focusable)
void
setFocusableInTouchMode(boolean focusableInTouchMode)
void
setFocusedByDefault(boolean isFocusedByDefault)
void
setForceDarkAllowed(boolean allow)
void
setForeground(Drawable foreground)
void
setForegroundGravity(int gravity)
void
void
void
void
setHandwritingBoundsOffsets(
    float offsetLeft,
    float offsetTop,
    float offsetRight,
    float offsetBottom
)
void
void
setHapticFeedbackEnabled(boolean hapticFeedbackEnabled)
void
setHasTransientState(boolean hasTransientState)
void
setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled)
void
setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled)
void
void
void
setHovered(boolean hovered)
void
setId(int id)
void
void
void
void
setIsCredential(boolean isCredential)
void
setIsHandwritingDelegate(boolean isHandwritingDelegate)
void
setKeepScreenOn(boolean keepScreenOn)
void
setKeyboardNavigationCluster(boolean isCluster)
void
setLabelFor(int id)
void
void
setLayerType(int layerType, Paint paint)
void
final void
setLeft(int left)
final void
setLeftTopRightBottom(int left, int top, int right, int bottom)
void
setLongClickable(boolean longClickable)
final void
setMeasuredDimension(int measuredWidth, int measuredHeight)
void
setMinimumHeight(int minHeight)
void
setMinimumWidth(int minWidth)
void
setNestedScrollingEnabled(boolean enabled)
void
setNextClusterForwardId(int nextClusterForwardId)
void
setNextFocusDownId(int nextFocusDownId)
void
setNextFocusForwardId(int nextFocusForwardId)
void
setNextFocusLeftId(int nextFocusLeftId)
void
setNextFocusRightId(int nextFocusRightId)
void
setNextFocusUpId(int nextFocusUpId)
void
void
void
void
void
void
void
void
void
void
void
void
setOnReceiveContentListener(
    String[] mimeTypes,
    OnReceiveContentListener listener
)
void
void

This method is deprecated.

void
void
void
void
void
setOverScrollMode(int overScrollMode)
void
setPadding(int left, int top, int right, int bottom)
void
setPaddingRelative(int start, int top, int end, int bottom)
void
setPivotX(float pivotX)
void
setPivotY(float pivotY)
void
final void
setPreferKeepClear(boolean preferKeepClear)
final void
void
setPressed(boolean pressed)
void
final void
setRevealOnFocusHint(boolean revealOnFocus)
final void
setRight(int right)
void
setRotation(float rotation)
void
setRotationX(float rotationX)
void
setRotationY(float rotationY)
void
setSaveEnabled(boolean enabled)
void
setSaveFromParentEnabled(boolean enabled)
void
setScaleX(float scaleX)
void
setScaleY(float scaleY)
void
setScreenReaderFocusable(boolean screenReaderFocusable)
void
setScrollBarDefaultDelayBeforeFade(
    int scrollBarDefaultDelayBeforeFade
)
void
setScrollBarFadeDuration(int scrollBarFadeDuration)
void
setScrollBarSize(int scrollBarSize)
void
setScrollBarStyle(int style)
final void
void
void
setScrollContainer(boolean isScrollContainer)
void
setScrollIndicators(int indicators)
void
setScrollX(int value)
void
setScrollY(int value)
void
setScrollbarFadingEnabled(boolean fadeScrollbars)
void
setSelected(boolean selected)
void
setSoundEffectsEnabled(boolean soundEffectsEnabled)
void
void
void
void
setSystemUiVisibility(int visibility)

This method is deprecated.

void
void
setTextAlignment(int textAlignment)
void
setTextDirection(int textDirection)
void
final void
setTop(int top)
void
void
setTransitionAlpha(float alpha)
final void
setTransitionName(String transitionName)
void
setTransitionVisibility(int visibility)
void
setTranslationX(float translationX)
void
setTranslationY(float translationY)
void
setTranslationZ(float translationZ)
void
setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled)
void
setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled)
void
void
void
void
void
setVisibility(int visibility)
void
setWillNotCacheDrawing(boolean willNotCacheDrawing)

This method is deprecated.

void
setWillNotDraw(boolean willNotDraw)
void
setX(float x)
void
setY(float y)
void
setZ(float z)
boolean
ActionMode
void
final boolean
startDrag(
    ClipData data,
    View.DragShadowBuilder shadowBuilder,
    Object myLocalState,
    int flags
)

This method is deprecated.

final boolean
startDragAndDrop(
    ClipData data,
    View.DragShadowBuilder shadowBuilder,
    Object myLocalState,
    int flags
)
boolean
void
String
void
void
void
final void
boolean
boolean

This method is deprecated.

boolean
From android.view.ViewGroup
void
void
addExtraDataToAccessibilityNodeInfo(
    AccessibilityNodeInfo info,
    String extraDataKey,
    Bundle arguments
)
void
addFocusables(ArrayList<View> views, int direction, int focusableMode)
void
boolean
void
void
addView(View child)
boolean
addViewInLayout(View child, int index, ViewGroup.LayoutParams params)
void
attachLayoutAnimationParameters(
    View child,
    ViewGroup.LayoutParams params,
    int index,
    int count
)
void
attachViewToParent(View child, int index, ViewGroup.LayoutParams params)
void
boolean
boolean
void
void
childHasTransientStateChanged(
    View child,
    boolean childHasTransientState
)
void
void
void
void
void
debug(int depth)
void
void
void
detachViewsFromParent(int start, int count)
WindowInsets
boolean
void
void
dispatchCreateViewTranslationRequest(
    Map<AutofillId, long[]> viewIds,
    int[] supportedFormats,
    TranslationCapability capability,
    List<ViewTranslationRequest> requests
)
void
boolean
void
void
dispatchDrawableHotspotChanged(float x, float y)
void
void
boolean
boolean
boolean
boolean
boolean
boolean
void
dispatchPointerCaptureChanged(boolean hasCapture)
void
void
void
void
dispatchScrollCaptureSearch(
    Rect localVisibleRect,
    Point windowOffset,
    Consumer<ScrollCaptureTarget> targets
)
void
dispatchSetActivated(boolean activated)
void
dispatchSetPressed(boolean pressed)
void
dispatchSetSelected(boolean selected)
void
void

This method is deprecated.

void
boolean
boolean
boolean
dispatchUnhandledMove(View focused, int direction)
void
dispatchVisibilityChanged(View changedView, int visibility)
void
dispatchWindowFocusChanged(boolean hasFocus)
void
void
WindowInsets
WindowInsetsAnimation.Bounds
void

This method is deprecated.

void
boolean
drawChild(Canvas canvas, View child, long drawingTime)
void
void
View
OnBackInvokedDispatcher
void
findViewsWithText(
    ArrayList<View> outViews,
    CharSequence text,
    int flags
)
View
focusSearch(View focused, int direction)
void
boolean
ViewGroup.LayoutParams
ViewGroup.LayoutParams
View
getChildAt(int index)
int
int
getChildDrawingOrder(int childCount, int drawingPosition)
static int
getChildMeasureSpec(int spec, int padding, int childDimension)
boolean
boolean
getChildVisibleRect(View child, Rect r, Point offset)
boolean
boolean
int
View
LayoutAnimationController
Animation.AnimationListener
int
LayoutTransition
int
ViewGroupOverlay
int

This method is deprecated.

boolean
boolean
boolean
int
final void
invalidateChild(View child, Rect dirty)

This method is deprecated.

ViewParent
invalidateChildInParent(int[] location, Rect dirty)

This method is deprecated.

boolean

This method is deprecated.

boolean

This method is deprecated.

boolean
boolean

This method is deprecated.

boolean
boolean
boolean
void
final void
layout(int l, int t, int r, int b)
void
measureChild(
    View child,
    int parentWidthMeasureSpec,
    int parentHeightMeasureSpec
)
void
measureChildWithMargins(
    View child,
    int parentWidthMeasureSpec,
    int widthUsed,
    int parentHeightMeasureSpec,
    int heightUsed
)
void
measureChildren(int widthMeasureSpec, int heightMeasureSpec)
void
notifySubtreeAccessibilityStateChanged(
    View child,
    View source,
    int changeType
)
final void
final void
void
int[]
onCreateDrawableState(int extraSpace)
void
void
boolean
boolean
boolean
onNestedFling(
    View target,
    float velocityX,
    float velocityY,
    boolean consumed
)
boolean
onNestedPreFling(View target, float velocityX, float velocityY)
boolean
onNestedPrePerformAccessibilityAction(
    View target,
    int action,
    Bundle args
)
void
onNestedPreScroll(View target, int dx, int dy, int[] consumed)
void
onNestedScroll(
    View target,
    int dxConsumed,
    int dyConsumed,
    int dxUnconsumed,
    int dyUnconsumed
)
void
onNestedScrollAccepted(View child, View target, int axes)
boolean
onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect)
boolean
PointerIcon
onResolvePointerIcon(MotionEvent event, int pointerIndex)
boolean
onStartNestedScroll(View child, View target, int nestedScrollAxes)
void
void
void
void
void
void
removeDetachedView(View child, boolean animate)
void
void
removeViewAt(int index)
void
void
removeViews(int start, int count)
void
removeViewsInLayout(int start, int count)
void
requestChildFocus(View child, View focused)
boolean
requestChildRectangleOnScreen(
    View child,
    Rect rectangle,
    boolean immediate
)
void
requestDisallowInterceptTouchEvent(boolean disallowIntercept)
boolean
requestFocus(int direction, Rect previouslyFocusedRect)
boolean
void
boolean
void
void
setAddStatesFromChildren(boolean addsStates)
void

This method is deprecated.

void
setAnimationCacheEnabled(boolean enabled)

This method is deprecated.

void

This method is deprecated.

void
void

This method is deprecated.

void
setClipChildren(boolean clipChildren)
void
setClipToPadding(boolean clipToPadding)
void
setDescendantFocusability(int focusability)
void
void
void
setLayoutMode(int layoutMode)
void
void
void
void
setPersistentDrawingCache(int drawingCacheToKeep)

This method is deprecated.

void
void
setTouchscreenBlocksFocus(boolean touchscreenBlocksFocus)
void
setTransitionGroup(boolean isTransitionGroup)
void
boolean
boolean
ActionMode
startActionModeForChild(
    View originalView,
    ActionMode.Callback callback
)
void
void
void
suppressLayout(boolean suppress)
void

Constants

OFFSCREEN_PAGE_LIMIT_DEFAULT

Added in 1.0.0
public static final int OFFSCREEN_PAGE_LIMIT_DEFAULT = -1

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.

ORIENTATION_HORIZONTAL

Added in 1.0.0
public static final int ORIENTATION_HORIZONTAL = 0

ORIENTATION_VERTICAL

Added in 1.0.0
public static final int ORIENTATION_VERTICAL = 1

SCROLL_STATE_DRAGGING

Added in 1.0.0
public static final int SCROLL_STATE_DRAGGING = 1

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

SCROLL_STATE_IDLE

Added in 1.0.0
public static final int SCROLL_STATE_IDLE = 0

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

SCROLL_STATE_SETTLING

Added in 1.0.0
public static final int SCROLL_STATE_SETTLING = 2

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

Public constructors

ViewPager2

Added in 1.0.0
public ViewPager2(@NonNull Context context)

ViewPager2

Added in 1.0.0
public ViewPager2(@NonNull Context context, @Nullable AttributeSet attrs)

ViewPager2

Added in 1.0.0
public ViewPager2(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr
)

ViewPager2

Added in 1.0.0
@RequiresApi(value = 21)
public ViewPager2(
    @NonNull Context context,
    @Nullable AttributeSet attrs,
    int defStyleAttr,
    int defStyleRes
)

Public methods

addItemDecoration

Added in 1.0.0
public void addItemDecoration(@NonNull RecyclerView.ItemDecoration decor)

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
@NonNull RecyclerView.ItemDecoration decor

Decoration to add

addItemDecoration

Added in 1.0.0
public void addItemDecoration(@NonNull RecyclerView.ItemDecoration decor, int index)

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
@NonNull RecyclerView.ItemDecoration decor

Decoration to add

int index

Position in the decoration chain to insert this decoration at. If this value is negative the decoration will be added at the end.

beginFakeDrag

Added in 1.0.0
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 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. 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

canScrollHorizontally

public boolean canScrollHorizontally(int direction)

canScrollVertically

public boolean canScrollVertically(int direction)

endFakeDrag

Added in 1.0.0
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

Added in 1.0.0
public boolean fakeDragBy(@Px 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
@Px float offsetPxFloat

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

@RequiresApi(value = 23)
public CharSequence getAccessibilityClassName()

getAdapter

Added in 1.0.0
public @Nullable RecyclerView.Adapter getAdapter()

getCurrentItem

Added in 1.0.0
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

Added in 1.0.0
public @NonNull RecyclerView.ItemDecoration getItemDecorationAt(int index)

Returns an ItemDecoration previously added to this ViewPager2.

Parameters
int index

The index position of the desired ItemDecoration.

Returns
@NonNull RecyclerView.ItemDecoration

the ItemDecoration at index position

Throws
java.lang.IndexOutOfBoundsException

on invalid index

getItemDecorationCount

Added in 1.0.0
public int getItemDecorationCount()

Returns the number of ItemDecoration currently added to this ViewPager2.

Returns
int

number of ItemDecorations currently added added to this ViewPager2.

getOffscreenPageLimit

Added in 1.0.0
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

Added in 1.0.0
public int getOrientation()

getScrollState

Added in 1.0.0
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 onPageScrollStateChanged

invalidateItemDecorations

Added in 1.0.0
public void invalidateItemDecorations()

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

isFakeDragging

Added in 1.0.0
public boolean isFakeDragging()

Returns true if a fake drag is in progress.

Returns
boolean

true if currently in a fake drag, false otherwise.

isUserInputEnabled

Added in 1.0.0
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)

onViewAdded

public void onViewAdded(View child)

performAccessibilityAction

public boolean performAccessibilityAction(int action, @Nullable Bundle arguments)

registerOnPageChangeCallback

Added in 1.0.0
public void registerOnPageChangeCallback(
    @NonNull ViewPager2.OnPageChangeCallback callback
)

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
@NonNull ViewPager2.OnPageChangeCallback callback

callback to add

removeItemDecoration

Added in 1.0.0
public void removeItemDecoration(@NonNull RecyclerView.ItemDecoration decor)

Remove an ItemDecoration from this ViewPager2.

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

Parameters
@NonNull RecyclerView.ItemDecoration decor

Decoration to remove

removeItemDecorationAt

Added in 1.0.0
public void removeItemDecorationAt(int index)

Removes the ItemDecoration associated with the supplied index position.

Parameters
int index

The index position of the ItemDecoration to be removed.

Throws
java.lang.IndexOutOfBoundsException

on invalid index

requestTransform

Added in 1.0.0
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

Added in 1.0.0
public void setAdapter(@Nullable RecyclerView.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
@Nullable RecyclerView.Adapter adapter

The adapter to use, or null to remove the current adapter

setCurrentItem

Added in 1.0.0
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.

Parameters
int item

Item index to select

setCurrentItem

Added in 1.0.0
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
int item

Item index to select

boolean smoothScroll

True to smoothly scroll to the new item, false to transition immediately

setLayoutDirection

public void setLayoutDirection(int layoutDirection)

setOffscreenPageLimit

Added in 1.0.0
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
int limit

How many pages will be kept offscreen on either side. Valid values are all values >= 1 and OFFSCREEN_PAGE_LIMIT_DEFAULT

Throws
java.lang.IllegalArgumentException

If the given limit is invalid

setOrientation

Added in 1.0.0
public void setOrientation(int orientation)

Sets the orientation of the ViewPager2.

Parameters
int orientation

ORIENTATION_HORIZONTAL or ORIENTATION_VERTICAL

setPageTransformer

Added in 1.0.0
public void setPageTransformer(@Nullable ViewPager2.PageTransformer transformer)

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
@Nullable ViewPager2.PageTransformer transformer

PageTransformer that will modify each page's animation properties

setUserInputEnabled

Added in 1.0.0
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
boolean enabled

true to allow user initiated scrolling, false to block user initiated scrolling

unregisterOnPageChangeCallback

Added in 1.0.0
public void unregisterOnPageChangeCallback(
    @NonNull ViewPager2.OnPageChangeCallback callback
)

Remove a callback that was previously added via registerOnPageChangeCallback.

Parameters
@NonNull ViewPager2.OnPageChangeCallback callback

callback to remove

Protected methods

dispatchRestoreInstanceState

protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container)

onLayout

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

onMeasure

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

onRestoreInstanceState

protected void onRestoreInstanceState(Parcelable state)

onSaveInstanceState

protected @Nullable Parcelable onSaveInstanceState()