ViewPager2

class ViewPager2 : 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

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

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

Constants

const 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.

const Int
const Int
const Int

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

const Int

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

const Int

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

Public constructors

ViewPager2(context: Context)
ViewPager2(context: Context, attrs: AttributeSet?)
ViewPager2(context: Context, attrs: AttributeSet?, defStyleAttr: Int)
@RequiresApi(value = 21)
ViewPager2(
    context: Context,
    attrs: AttributeSet?,
    defStyleAttr: Int,
    defStyleRes: Int
)

Public functions

Unit

Add an ItemDecoration to this ViewPager2.

Unit

Add an ItemDecoration to this ViewPager2.

Boolean

Start a fake drag of the pager.

Boolean
Boolean
Boolean

End a fake drag of the pager.

Boolean
fakeDragBy(offsetPxFloat: @Px Float)

Fake drag by an offset in pixels.

CharSequence!
RecyclerView.Adapter?
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
@RequiresApi(value = 16)
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 transformPage 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
@RequiresApi(value = 17)
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.

Protected functions

Unit
Unit
onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int)
Unit
onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int)
Unit
Parcelable?

Inherited Constants

From android.view.View
const Int
const Int
const Int
const Int
const Int
const Int
const Property<View!, Float!>!
const Int
const String!
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE = "creditCardExpirationDate"
const String!
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY = "creditCardExpirationDay"
const String!
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH = "creditCardExpirationMonth"
const String!
AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR = "creditCardExpirationYear"
const String!
const String!
AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE = "creditCardSecurityCode"
const String!
const String!
const String!
const String!
const String!
const String!
const String!
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int

This property is deprecated.

const Int

This property is deprecated.

const Int

This property is deprecated.

const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const Int
const Int
const Int
const Int
const Int
const Int
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const Int
const Int
const Int
const Int
const Int
const Int
const Int
GONE = 8
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
KEEP_SCREEN_ON = 67108864
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
NO_ID = -1
const Int
const Int
const Int
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const IntArray<Int>!
const Property<View!, Float!>!
const Property<View!, Float!>!
const Property<View!, Float!>!
const Property<View!, Float!>!
const Property<View!, Float!>!
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const IntArray<Int>!
const IntArray<Int>!
const Int
const Int

This property is deprecated.

const Int

This property is deprecated.

const Int

This property is deprecated.

const Int

This property is deprecated.

const Int

This property is deprecated.

const Int

This property is deprecated.

const Int

This property is deprecated.

const Int

This property is deprecated.

const Int

This property is deprecated.

const Int

This property is deprecated.

const Int

This property is deprecated.

const Int

This property is deprecated.

const Int

This property is deprecated.

const Int

This property is deprecated.

const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Int
const Property<View!, Float!>!
const Property<View!, Float!>!
const Property<View!, Float!>!
const String!
VIEW_LOG_TAG = "View"
const Int
const IntArray<Int>!
const Property<View!, Float!>!
const Property<View!, Float!>!
const Property<View!, Float!>!
From android.view.ViewGroup
const Int
const Int
const Int
const Int
const Int
const Int
const Int

This property is deprecated.

const Int

This property is deprecated.

const Int

This property is deprecated.

const Int

This property is deprecated.

Inherited functions

From android.view.View
Unit
Unit
Unit
ViewPropertyAnimator!
Unit
Unit
Boolean
Unit
Unit

This function is deprecated.

Unit
Boolean
Boolean
Boolean
Boolean
Unit
Unit
Unit
Boolean
Unit
Unit
java-static Int
combineMeasuredStates(curState: Int, newState: Int)
Int
Int
Int
Unit
WindowInsets!
computeSystemWindowInsets(in: WindowInsets!, outLocalInsets: Rect!)
Int
Int
Int
AccessibilityNodeInfo!
Unit
Unit

This function is deprecated.

Boolean
Boolean
dispatchNestedFling(velocityX: Float, velocityY: Float, consumed: Boolean)
Boolean
dispatchNestedPreFling(velocityX: Float, velocityY: Float)
Boolean
dispatchNestedPrePerformAccessibilityAction(
    action: Int,
    arguments: Bundle!
)
Boolean
dispatchNestedPreScroll(
    dx: Int,
    dy: Int,
    consumed: IntArray!,
    offsetInWindow: IntArray!
)
Boolean
dispatchNestedScroll(
    dxConsumed: Int,
    dyConsumed: Int,
    dxUnconsumed: Int,
    dyUnconsumed: Int,
    offsetInWindow: IntArray!
)
Boolean
Unit
draw(canvas: Canvas!)
Unit
OnBackInvokedDispatcher!
T!
<T : View?> findViewById(id: Int)
T!
<T : View?> findViewWithTag(tag: Any!)
Boolean

This function is deprecated.

Unit
forceHasOverlappingRendering(hasOverlappingRendering: Boolean)
Unit
Unit
generateDisplayHash(
    hashAlgorithm: String!,
    bounds: Rect!,
    executor: Executor!,
    callback: DisplayHashResultCallback!
)
java-static Int
View.AccessibilityDelegate!
Int
AccessibilityNodeProvider!
CharSequence!
Int
Int
String!
String!
Float
Animation!
Matrix!
IBinder!
IntArray<Int>!
(Mutable)Map<Int!, Int!>!
Array<String!>!
AutofillId!
Int
AutofillValue!
Drawable!
BlendMode!
ColorStateList!
PorterDuff.Mode!
Int
Int
Float
Int
Float
Rect!
Boolean
getClipBounds(outRect: Rect!)
Boolean
ContentCaptureSession!
CharSequence!
Context!
ContextMenu.ContextMenuInfo!
Boolean
java-static Int
getDefaultSize(size: Int, measureSpec: Int)
Display!
IntArray<Int>!
Bitmap!

This function is deprecated.

Int

This function is deprecated.

Int

This function is deprecated.

Unit
getDrawingRect(outRect: Rect!)
Long
Float
Int
Boolean
Boolean
Int
ArrayList<View!>!
getFocusables(direction: Int)
Unit
Drawable!
Int
BlendMode!
ColorStateList!
PorterDuff.Mode!
Boolean
getGlobalVisibleRect(r: Rect!, globalOffset: Point!)
Handler!
Float
Float
Float
Float
Runnable!
Boolean
Int
Unit
getHitRect(outRect: Rect!)
Int
Int
Drawable!
Drawable!
Int
Int
Int
Int
Boolean
KeyEvent.DispatcherState!
Int
Int
Int
ViewGroup.LayoutParams!
Int
Float
Int
Boolean
Unit
Unit
Unit
Matrix!
Int
Int
Int
Int
Int
Int
Int
Int
Int
Int
Int
Int
Int
View.OnFocusChangeListener!
Int
ViewOutlineProvider!
Int
Int
ViewOverlay!
Int
Int
Int
Int
Int
Int
ViewParent!
ViewParent!
Float
Float
PointerIcon!
(Mutable)List<Rect!>!
Array<String!>!
Resources!
Boolean
Int
Float
Int
AttachedSurfaceControl!
View!
WindowInsets!
Float
Float
Float
Float
Float
Int
Int
Int
Int
Int
Int
Int
Int
Int
Int
CharSequence!
StateListAnimator!
Int
Int
(Mutable)List<Rect!>!
Int

This function is deprecated.

Any!
Int
Int
CharSequence!
Int
Float
Int
TouchDelegate!
ArrayList<View!>!
Float
String!
Float
Float
Float
Long
Int
Int
Drawable!
Drawable!
Int
ViewTranslationResponse!
ViewTreeObserver!
Int
Int
Int
WindowId!
WindowInsetsController!
Int

This function is deprecated.

IBinder!
Int
Unit
Float
Float
Float
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
java-static View!
inflate(context: Context!, resource: Int, root: ViewGroup!)
Unit
invalidate(dirty: Rect!)

This function is deprecated.

Unit
Unit
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean

This function is deprecated.

Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
View!
keyboardNavigationClusterSearch(currentCluster: View!, direction: Int)
Unit
measure(widthMeasureSpec: Int, heightMeasureSpec: Int)
java-static IntArray<Int>!
mergeDrawableStates(baseState: IntArray!, additionalState: IntArray!)
Unit
Unit
Unit
Unit
WindowInsets!
Unit
Boolean
Boolean
Unit
Unit
InputConnection!
Unit
onCreateViewTranslationRequest(
    supportedFormats: IntArray!,
    requestsCollector: Consumer<ViewTranslationRequest!>!
)
Unit
onCreateVirtualViewTranslationRequests(
    virtualIds: LongArray!,
    supportedFormats: IntArray!,
    requestsCollector: Consumer<ViewTranslationRequest!>!
)
Unit
Boolean
Unit
onDraw(canvas: Canvas!)
Unit
Unit
Boolean
Unit
Unit
Unit
onFocusChanged(
    gainFocus: Boolean,
    direction: Int,
    previouslyFocusedRect: Rect!
)
Boolean
Unit
Boolean
Unit
Boolean
onKeyDown(keyCode: Int, event: KeyEvent!)
Boolean
onKeyLongPress(keyCode: Int, event: KeyEvent!)
Boolean
onKeyMultiple(keyCode: Int, repeatCount: Int, event: KeyEvent!)
Boolean
onKeyPreIme(keyCode: Int, event: KeyEvent!)
Boolean
onKeyShortcut(keyCode: Int, event: KeyEvent!)
Boolean
onKeyUp(keyCode: Int, event: KeyEvent!)
Unit
onOverScrolled(
    scrollX: Int,
    scrollY: Int,
    clampedX: Boolean,
    clampedY: Boolean
)
Unit
Unit
Unit
Unit
Unit
Unit
Unit
ContentInfo!
Unit
onRtlPropertiesChanged(layoutDirection: Int)
Unit
onScreenStateChanged(screenState: Int)
Unit
onScrollCaptureSearch(
    localVisibleRect: Rect!,
    windowOffset: Point!,
    targets: Consumer<ScrollCaptureTarget!>!
)
Unit
onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int)
Boolean
onSetAlpha(alpha: Int)
Unit
onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int)
Unit
Boolean
Boolean
Unit
Unit
Unit
Unit
onVisibilityChanged(changedView: View!, visibility: Int)
Unit
onWindowFocusChanged(hasWindowFocus: Boolean)
Unit

This function is deprecated.

Unit
Boolean
overScrollBy(
    deltaX: Int,
    deltaY: Int,
    scrollX: Int,
    scrollY: Int,
    scrollRangeX: Int,
    scrollRangeY: Int,
    maxOverScrollX: Int,
    maxOverScrollY: Int,
    isTouchEvent: Boolean
)
Boolean
Boolean
Boolean
performHapticFeedback(feedbackConstant: Int)
Boolean
ContentInfo!
Unit
playSoundEffect(soundConstant: Int)
Boolean
post(action: Runnable!)
Boolean
postDelayed(action: Runnable!, delayMillis: Long)
Unit
Unit
postInvalidateDelayed(delayMilliseconds: Long)
Unit
Unit
Unit
postOnAnimationDelayed(action: Runnable!, delayMillis: Long)
Unit
Unit
Boolean
Unit
Unit
Unit
Unit
Unit

This function is deprecated.

Boolean
Unit
Unit
Boolean
Unit
T!
<T : View?> requireViewById(id: Int)
Unit
java-static Int
resolveSize(size: Int, measureSpec: Int)
java-static Int
resolveSizeAndState(size: Int, measureSpec: Int, childMeasuredState: Int)
Unit
Unit
saveAttributeDataForStyleable(
    context: Context!,
    styleable: IntArray!,
    attrs: AttributeSet!,
    t: TypedArray!,
    defStyleAttr: Int,
    defStyleRes: Int
)
Unit
Unit
scheduleDrawable(who: Drawable!, what: Runnable!, when: Long)
Unit
scrollBy(x: Int, y: Int)
Unit
scrollTo(x: Int, y: Int)
Unit
Unit
Unit
setAccessibilityDataSensitive(accessibilityDataSensitive: Int)
Unit
Unit
Unit
Unit
setAccessibilityPaneTitle(accessibilityPaneTitle: CharSequence!)
Unit
Unit
Unit
setActivated(activated: Boolean)
Unit
setAllowClickWhenDisabled(clickableWhenDisabled: Boolean)
Unit
Unit
Unit
setAlpha(alpha: Float)
Unit
setAnimation(animation: Animation!)
Unit
Unit
Unit
setAutofillHints(autofillHints: Array<String!>!)
Unit
Unit
setBackground(background: Drawable!)
Unit
Unit

This function is deprecated.

Unit
Unit
Unit
Unit
Unit
setBottom(bottom: Int)
Unit
Unit
setClickable(clickable: Boolean)
Unit
setClipBounds(clipBounds: Rect!)
Unit
setClipToOutline(clipToOutline: Boolean)
Unit
Unit
setContentDescription(contentDescription: CharSequence!)
Unit
setContextClickable(contextClickable: Boolean)
Unit
setDefaultFocusHighlightEnabled(defaultFocusHighlightEnabled: Boolean)
Unit

This function is deprecated.

Unit

This function is deprecated.

Unit

This function is deprecated.

Unit
Unit
setElevation(elevation: Float)
Unit
setEnabled(enabled: Boolean)
Unit
Unit
Unit
setFitsSystemWindows(fitSystemWindows: Boolean)
Unit
setFocusable(focusable: Boolean)
Unit
setFocusableInTouchMode(focusableInTouchMode: Boolean)
Unit
setFocusedByDefault(isFocusedByDefault: Boolean)
Unit
Unit
setForeground(foreground: Drawable!)
Unit
Unit
Unit
Unit
Unit
setHandwritingBoundsOffsets(
    offsetLeft: Float,
    offsetTop: Float,
    offsetRight: Float,
    offsetBottom: Float
)
Unit
Unit
setHapticFeedbackEnabled(hapticFeedbackEnabled: Boolean)
Unit
setHasTransientState(hasTransientState: Boolean)
Unit
setHorizontalFadingEdgeEnabled(horizontalFadingEdgeEnabled: Boolean)
Unit
setHorizontalScrollBarEnabled(horizontalScrollBarEnabled: Boolean)
Unit
Unit
Unit
setHovered(hovered: Boolean)
Unit
setId(id: Int)
Unit
Unit
Unit
Unit
setIsCredential(isCredential: Boolean)
Unit
setIsHandwritingDelegate(isHandwritingDelegate: Boolean)
Unit
setKeepScreenOn(keepScreenOn: Boolean)
Unit
Unit
Unit
Unit
setLayerType(layerType: Int, paint: Paint!)
Unit
Unit
setLeft(left: Int)
Unit
setLeftTopRightBottom(left: Int, top: Int, right: Int, bottom: Int)
Unit
setLongClickable(longClickable: Boolean)
Unit
setMeasuredDimension(measuredWidth: Int, measuredHeight: Int)
Unit
setMinimumHeight(minHeight: Int)
Unit
setMinimumWidth(minWidth: Int)
Unit
Unit
setNextClusterForwardId(nextClusterForwardId: Int)
Unit
setNextFocusDownId(nextFocusDownId: Int)
Unit
setNextFocusForwardId(nextFocusForwardId: Int)
Unit
setNextFocusLeftId(nextFocusLeftId: Int)
Unit
setNextFocusRightId(nextFocusRightId: Int)
Unit
setNextFocusUpId(nextFocusUpId: Int)
Unit
Unit
Unit
Unit
Unit
Unit
Unit
Unit
Unit
Unit
Unit
Unit
setOnReceiveContentListener(
    mimeTypes: Array<String!>!,
    listener: OnReceiveContentListener!
)
Unit
Unit

This function is deprecated.

Unit
Unit
Unit
Unit
Unit
setOverScrollMode(overScrollMode: Int)
Unit
setPadding(left: Int, top: Int, right: Int, bottom: Int)
Unit
setPaddingRelative(start: Int, top: Int, end: Int, bottom: Int)
Unit
setPivotX(pivotX: Float)
Unit
setPivotY(pivotY: Float)
Unit
setPointerIcon(pointerIcon: PointerIcon!)
Unit
setPreferKeepClear(preferKeepClear: Boolean)
Unit
Unit
setPressed(pressed: Boolean)
Unit
setRenderEffect(renderEffect: RenderEffect!)
Unit
setRevealOnFocusHint(revealOnFocus: Boolean)
Unit
setRight(right: Int)
Unit
setRotation(rotation: Float)
Unit
setRotationX(rotationX: Float)
Unit
setRotationY(rotationY: Float)
Unit
Unit
Unit
setScaleX(scaleX: Float)
Unit
setScaleY(scaleY: Float)
Unit
setScreenReaderFocusable(screenReaderFocusable: Boolean)
Unit
setScrollBarDefaultDelayBeforeFade(
    scrollBarDefaultDelayBeforeFade: Int
)
Unit
setScrollBarFadeDuration(scrollBarFadeDuration: Int)
Unit
setScrollBarSize(scrollBarSize: Int)
Unit
Unit
Unit
Unit
setScrollContainer(isScrollContainer: Boolean)
Unit
setScrollIndicators(indicators: Int)
Unit
setScrollX(value: Int)
Unit
setScrollY(value: Int)
Unit
Unit
setSelected(selected: Boolean)
Unit
setSoundEffectsEnabled(soundEffectsEnabled: Boolean)
Unit
setStateDescription(stateDescription: CharSequence!)
Unit
Unit
Unit

This function is deprecated.

Unit
setTag(tag: Any!)
Unit
setTextAlignment(textAlignment: Int)
Unit
setTextDirection(textDirection: Int)
Unit
Unit
setTop(top: Int)
Unit
Unit
Unit
setTransitionName(transitionName: String!)
Unit
Unit
setTranslationX(translationX: Float)
Unit
setTranslationY(translationY: Float)
Unit
setTranslationZ(translationZ: Float)
Unit
setVerticalFadingEdgeEnabled(verticalFadingEdgeEnabled: Boolean)
Unit
setVerticalScrollBarEnabled(verticalScrollBarEnabled: Boolean)
Unit
Unit
Unit
Unit
Unit
setVisibility(visibility: Int)
Unit
setWillNotCacheDrawing(willNotCacheDrawing: Boolean)

This function is deprecated.

Unit
setWillNotDraw(willNotDraw: Boolean)
Unit
setX(x: Float)
Unit
setY(y: Float)
Unit
setZ(z: Float)
Boolean
ActionMode!
Unit
Boolean
startDrag(
    data: ClipData!,
    shadowBuilder: View.DragShadowBuilder!,
    myLocalState: Any!,
    flags: Int
)

This function is deprecated.

Boolean
startDragAndDrop(
    data: ClipData!,
    shadowBuilder: View.DragShadowBuilder!,
    myLocalState: Any!,
    flags: Int
)
Boolean
Unit
String!
Unit
Unit
Unit
Unit
Boolean
Boolean

This function is deprecated.

Boolean
From android.view.ViewGroup
Unit
Unit
addExtraDataToAccessibilityNodeInfo(
    info: AccessibilityNodeInfo!,
    extraDataKey: String!,
    arguments: Bundle!
)
Unit
addFocusables(views: ArrayList<View!>!, direction: Int, focusableMode: Int)
Unit
addKeyboardNavigationClusters(
    views: (Mutable)Collection<View!>!,
    direction: Int
)
Boolean
Unit
Unit
addView(child: View!)
Boolean
addViewInLayout(child: View!, index: Int, params: ViewGroup.LayoutParams!)
Unit
attachLayoutAnimationParameters(
    child: View!,
    params: ViewGroup.LayoutParams!,
    index: Int,
    count: Int
)
Unit
attachViewToParent(child: View!, index: Int, params: ViewGroup.LayoutParams!)
Unit
Boolean
Boolean
Unit
Unit
childHasTransientStateChanged(
    child: View!,
    childHasTransientState: Boolean
)
Unit
Unit
Unit
Unit
Unit
debug(depth: Int)
Unit
Unit
Unit
detachViewsFromParent(start: Int, count: Int)
WindowInsets!
Boolean
Unit
Unit
dispatchCreateViewTranslationRequest(
    viewIds: (Mutable)Map<AutofillId!, LongArray!>!,
    supportedFormats: IntArray!,
    capability: TranslationCapability!,
    requests: (Mutable)List<ViewTranslationRequest!>!
)
Unit
Boolean
Unit
dispatchDraw(canvas: Canvas!)
Unit
Unit
Unit
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Unit
Unit
Unit
Unit
Unit
dispatchScrollCaptureSearch(
    localVisibleRect: Rect!,
    windowOffset: Point!,
    targets: Consumer<ScrollCaptureTarget!>!
)
Unit
Unit
Unit
Unit
Unit

This function is deprecated.

Unit
Boolean
Boolean
Boolean
dispatchUnhandledMove(focused: View!, direction: Int)
Unit
dispatchVisibilityChanged(changedView: View!, visibility: Int)
Unit
Unit
Unit
WindowInsets!
dispatchWindowInsetsAnimationProgress(
    insets: WindowInsets!,
    runningAnimations: (Mutable)List<WindowInsetsAnimation!>!
)
WindowInsetsAnimation.Bounds!
Unit

This function is deprecated.

Unit
Boolean
drawChild(canvas: Canvas!, child: View!, drawingTime: Long)
Unit
Unit
View!
OnBackInvokedDispatcher!
Unit
findViewsWithText(
    outViews: ArrayList<View!>!,
    text: CharSequence!,
    flags: Int
)
View!
focusSearch(focused: View!, direction: Int)
Unit
Boolean
ViewGroup.LayoutParams!
ViewGroup.LayoutParams!
View!
getChildAt(index: Int)
Int
Int
getChildDrawingOrder(childCount: Int, drawingPosition: Int)
java-static Int
getChildMeasureSpec(spec: Int, padding: Int, childDimension: Int)
Boolean
Boolean
getChildVisibleRect(child: View!, r: Rect!, offset: Point!)
Boolean
Boolean
Int
View!
LayoutAnimationController!
Animation.AnimationListener!
Int
LayoutTransition!
Int
ViewGroupOverlay!
Int

This function is deprecated.

Boolean
Boolean
Boolean
Int
indexOfChild(child: View!)
Unit
invalidateChild(child: View!, dirty: Rect!)

This function is deprecated.

ViewParent!
invalidateChildInParent(location: IntArray!, dirty: Rect!)

This function is deprecated.

Boolean

This function is deprecated.

Boolean

This function is deprecated.

Boolean
Boolean

This function is deprecated.

Boolean
Boolean
Boolean
Unit
Unit
layout(l: Int, t: Int, r: Int, b: Int)
Unit
measureChild(
    child: View!,
    parentWidthMeasureSpec: Int,
    parentHeightMeasureSpec: Int
)
Unit
measureChildWithMargins(
    child: View!,
    parentWidthMeasureSpec: Int,
    widthUsed: Int,
    parentHeightMeasureSpec: Int,
    heightUsed: Int
)
Unit
measureChildren(widthMeasureSpec: Int, heightMeasureSpec: Int)
Unit
notifySubtreeAccessibilityStateChanged(
    child: View!,
    source: View!,
    changeType: Int
)
Unit
offsetDescendantRectToMyCoords(descendant: View!, rect: Rect!)
Unit
offsetRectIntoDescendantCoords(descendant: View!, rect: Rect!)
Unit
IntArray<Int>!
Unit
onDescendantInvalidated(child: View!, target: View!)
Unit
Boolean
Boolean
Boolean
onNestedFling(
    target: View!,
    velocityX: Float,
    velocityY: Float,
    consumed: Boolean
)
Boolean
onNestedPreFling(target: View!, velocityX: Float, velocityY: Float)
Boolean
onNestedPrePerformAccessibilityAction(
    target: View!,
    action: Int,
    args: Bundle!
)
Unit
onNestedPreScroll(target: View!, dx: Int, dy: Int, consumed: IntArray!)
Unit
onNestedScroll(
    target: View!,
    dxConsumed: Int,
    dyConsumed: Int,
    dxUnconsumed: Int,
    dyUnconsumed: Int
)
Unit
onNestedScrollAccepted(child: View!, target: View!, axes: Int)
Boolean
onRequestFocusInDescendants(direction: Int, previouslyFocusedRect: Rect!)
Boolean
PointerIcon!
onResolvePointerIcon(event: MotionEvent!, pointerIndex: Int)
Boolean
onStartNestedScroll(child: View!, target: View!, nestedScrollAxes: Int)
Unit
Unit
Unit
Unit
Unit
Unit
removeDetachedView(child: View!, animate: Boolean)
Unit
removeView(view: View!)
Unit
removeViewAt(index: Int)
Unit
Unit
removeViews(start: Int, count: Int)
Unit
removeViewsInLayout(start: Int, count: Int)
Unit
requestChildFocus(child: View!, focused: View!)
Boolean
requestChildRectangleOnScreen(
    child: View!,
    rectangle: Rect!,
    immediate: Boolean
)
Unit
Boolean
requestFocus(direction: Int, previouslyFocusedRect: Rect!)
Boolean
Unit
Boolean
Unit
Unit
Unit

This function is deprecated.

Unit

This function is deprecated.

Unit

This function is deprecated.

Unit
Unit

This function is deprecated.

Unit
setClipChildren(clipChildren: Boolean)
Unit
setClipToPadding(clipToPadding: Boolean)
Unit
Unit
Unit
Unit
setLayoutMode(layoutMode: Int)
Unit
Unit
Unit
Unit
setPersistentDrawingCache(drawingCacheToKeep: Int)

This function is deprecated.

Unit
Unit
setTouchscreenBlocksFocus(touchscreenBlocksFocus: Boolean)
Unit
setTransitionGroup(isTransitionGroup: Boolean)
Unit
Boolean
Boolean
showContextMenuForChild(originalView: View!)
ActionMode!
startActionModeForChild(
    originalView: View!,
    callback: ActionMode.Callback!
)
Unit
Unit
Unit
Unit

Constants

OFFSCREEN_PAGE_LIMIT_DEFAULT

Added in 1.0.0
const val OFFSCREEN_PAGE_LIMIT_DEFAULT = -1: 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.

ORIENTATION_HORIZONTAL

Added in 1.0.0
const val ORIENTATION_HORIZONTAL = 0: Int

ORIENTATION_VERTICAL

Added in 1.0.0
const val ORIENTATION_VERTICAL = 1: Int

SCROLL_STATE_DRAGGING

Added in 1.0.0
const val SCROLL_STATE_DRAGGING = 1: Int

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
const val SCROLL_STATE_IDLE = 0: Int

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
const val SCROLL_STATE_SETTLING = 2: Int

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

Public constructors

ViewPager2

Added in 1.0.0
ViewPager2(context: Context)

ViewPager2

Added in 1.0.0
ViewPager2(context: Context, attrs: AttributeSet?)

ViewPager2

Added in 1.0.0
ViewPager2(context: Context, attrs: AttributeSet?, defStyleAttr: Int)

ViewPager2

Added in 1.0.0
@RequiresApi(value = 21)
ViewPager2(
    context: Context,
    attrs: AttributeSet?,
    defStyleAttr: Int,
    defStyleRes: Int
)

Public functions

addItemDecoration

Added in 1.0.0
fun addItemDecoration(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

Added in 1.0.0
fun addItemDecoration(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: Int

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

fun canScrollHorizontally(direction: Int): Boolean

canScrollVertically

fun canScrollVertically(direction: Int): Boolean

endFakeDrag

Added in 1.0.0
fun endFakeDrag(): Boolean

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
fun fakeDragBy(offsetPxFloat: @Px 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: @Px 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

@RequiresApi(value = 23)
fun getAccessibilityClassName(): CharSequence!

getAdapter

Added in 1.0.0
fun getAdapter(): RecyclerView.Adapter?

getCurrentItem

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

Returns
Int

Currently selected page

getItemDecorationAt

Added in 1.0.0
fun getItemDecorationAt(index: Int): RecyclerView.ItemDecoration

Returns an 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
java.lang.IndexOutOfBoundsException

on invalid index

getItemDecorationCount

Added in 1.0.0
fun getItemDecorationCount(): Int

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

Returns
Int

How many pages will be kept offscreen on either side

getOrientation

Added in 1.0.0
fun getOrientation(): Int

getScrollState

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

Returns
Int

The scroll state that was last dispatched to onPageScrollStateChanged

invalidateItemDecorations

Added in 1.0.0
fun invalidateItemDecorations(): Unit

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

isFakeDragging

Added in 1.0.0
fun isFakeDragging(): Boolean

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
fun isUserInputEnabled(): Boolean

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

Returns
Boolean

true if users can scroll the ViewPager2, false otherwise

onInitializeAccessibilityNodeInfo

fun onInitializeAccessibilityNodeInfo(info: AccessibilityNodeInfo!): Unit

onViewAdded

fun onViewAdded(child: View!): Unit

performAccessibilityAction

@RequiresApi(value = 16)
fun performAccessibilityAction(action: Int, arguments: Bundle?): Boolean

registerOnPageChangeCallback

Added in 1.0.0
fun registerOnPageChangeCallback(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

Added in 1.0.0
fun removeItemDecoration(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

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

Throws
java.lang.IndexOutOfBoundsException

on invalid index

requestTransform

Added in 1.0.0
fun requestTransform(): Unit

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
fun setAdapter(adapter: RecyclerView.Adapter?): 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 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: RecyclerView.Adapter?

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

setCurrentItem

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

Parameters
item: Int

Item index to select

setCurrentItem

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

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

setLayoutDirection

@RequiresApi(value = 17)
fun setLayoutDirection(layoutDirection: Int): Unit

setOffscreenPageLimit

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

Throws
java.lang.IllegalArgumentException

If the given limit is invalid

setOrientation

Added in 1.0.0
fun setOrientation(orientation: Int): Unit

Sets the orientation of the ViewPager2.

Parameters
orientation: Int

ORIENTATION_HORIZONTAL or ORIENTATION_VERTICAL

setPageTransformer

Added in 1.0.0
fun setPageTransformer(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

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

Added in 1.0.0
fun unregisterOnPageChangeCallback(
    callback: ViewPager2.OnPageChangeCallback
): Unit

Remove a callback that was previously added via registerOnPageChangeCallback.

Parameters
callback: ViewPager2.OnPageChangeCallback

callback to remove

Protected functions

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

protected fun onSaveInstanceState(): Parcelable?