ViewPager


public class ViewPager extends ViewGroup

Known direct subclasses
LeanbackViewPager

A viewpager with touch and key event handling disabled by default.


Layout manager that allows the user to flip left and right through pages of data. You supply an implementation of a PagerAdapter to generate the pages that the view shows.

ViewPager is most often used in conjunction with android.app.Fragment, which is a convenient way to supply and manage the lifecycle of each page. There are standard adapters implemented for using fragments with the ViewPager, which cover the most common use cases. These are androidx.fragment.app.FragmentPagerAdapter and androidx.fragment.app.FragmentStatePagerAdapter; each of these classes have simple code showing how to build a full user interface with them.

Views which are annotated with the DecorView annotation are treated as part of the view pagers 'decor'. Each decor view's position can be controlled via its android:layout_gravity attribute. For example:

<androidx.viewpager.widget.ViewPager
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.viewpager.widget.PagerTitleStrip
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top" />

</androidx.viewpager.widget.ViewPager>

For more information about how to use ViewPager, read Creating Swipe Views with Tabs.

You can find examples of using ViewPager in the API 4+ Support Demos and API 13+ Support Demos sample code.

Summary

Nested types

@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.TYPE)
@Inherited
public annotation ViewPager.DecorView

Annotation which allows marking of views to be decoration views when added to a view pager.

Layout parameters that should be supplied for views added to a ViewPager.

Callback interface for responding to adapter changes.

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

public interface ViewPager.PageTransformer

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

public class ViewPager.SavedState extends AbsSavedState

This is the persistent state that is saved by ViewPager.

Simple implementation of the OnPageChangeListener interface with stub implementations of each method.

Constants

static final int

Indicates that the pager is currently being dragged by the user.

static final int

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

static final int

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

Public constructors

Public methods

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

We only want the current page that is being shown to be focusable.

void

Add a listener that will be invoked whenever the adapter for this ViewPager changes.

void

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

void

We only want the current page that is being shown to be touchable.

void
addView(View child, int index, ViewGroup.LayoutParams params)
boolean
arrowScroll(int direction)

Handle scrolling in response to a left or right arrow click.

boolean

Start a fake drag of the pager.

boolean
canScrollHorizontally(int direction)

Check if this ViewPager can be scrolled horizontally in a certain direction.

void

Remove all listeners that are notified of any changes in scroll state or position.

void
boolean
boolean
void
draw(@NonNull Canvas canvas)
void

End a fake drag of the pager.

boolean

You can call this function yourself to have the scroll view perform scrolling from a key event, just as if the event had been dispatched to it by the view hierarchy.

void
fakeDragBy(float xOffset)

Fake drag by an offset in pixels.

ViewGroup.LayoutParams
@Nullable PagerAdapter

Retrieve the current adapter supplying pages.

int
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

Return the margin between pages.

boolean
boolean

Returns true if a fake drag is in progress.

boolean
void
@NonNull Parcelable
boolean
void

Remove a listener that was previously added via addOnAdapterChangeListener.

void

Remove a listener that was previously added via addOnPageChangeListener.

void
void

Set a PagerAdapter that will supply views for this pager as needed.

void
setCurrentItem(int item)

Set the currently selected page.

void
setCurrentItem(int item, boolean smoothScroll)

Set the currently selected page.

void
setDragInGutterEnabled(boolean enabled)

Set whether ViewPager should consume drag events if they are within the gutter (left and right edges) of the ViewPager.

void

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

void

This method is deprecated.

Use addOnPageChangeListener and removeOnPageChangeListener instead.

void
setPageMargin(int marginPixels)

Set the margin between pages.

void

Set a drawable that will be used to fill the margin between pages.

void

Set a drawable that will be used to fill the margin between pages.

void
setPageTransformer(
    boolean reverseDrawingOrder,
    @Nullable ViewPager.PageTransformer transformer
)

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

void
setPageTransformer(
    boolean reverseDrawingOrder,
    @Nullable ViewPager.PageTransformer transformer,
    int pageLayerType
)

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

Protected methods

boolean
canScroll(@NonNull View v, boolean checkV, int dx, int x, int y)

Tests scrollability within child views of v given a delta of dx.

boolean
void
ViewGroup.LayoutParams
ViewGroup.LayoutParams
int
getChildDrawingOrder(int childCount, int i)
void
void
void
void
onLayout(boolean changed, int l, int t, int r, int b)
void
onMeasure(int widthMeasureSpec, int heightMeasureSpec)
void
@CallSuper
onPageScrolled(int position, float offset, int offsetPixels)

This method will be invoked when the current page is scrolled, either as part of a programmatically initiated smooth scroll or a user initiated touch scroll.

boolean
onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect)

We only want the current page that is being shown to be focusable.

void
onSizeChanged(int w, int h, int oldw, int oldh)
boolean

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
boolean
canScrollVertically(int direction)
final void
void
final void
boolean
void
void
static int
combineMeasuredStates(int curState, int newState)
int
int
int
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
)
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
final void
boolean
void
void
void
onFocusChanged(
    boolean gainFocus,
    int direction,
    Rect previouslyFocusedRect
)
boolean
void
onHoverChanged(boolean hovered)
boolean
void
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
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
performAccessibilityAction(int action, Bundle arguments)
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
setLayoutDirection(int layoutDirection)
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

This method is deprecated.

boolean
From android.view.ViewGroup
void
void
addExtraDataToAccessibilityNodeInfo(
    AccessibilityNodeInfo info,
    String extraDataKey,
    Bundle arguments
)
void
boolean
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
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
void
dispatchPointerCaptureChanged(boolean hasCapture)
void
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
View
OnBackInvokedDispatcher
void
findViewsWithText(
    ArrayList<View> outViews,
    CharSequence text,
    int flags
)
View
focusSearch(View focused, int direction)
void
boolean
CharSequence
View
getChildAt(int index)
int
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
int[]
onCreateDrawableState(int extraSpace)
void
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
PointerIcon
onResolvePointerIcon(MotionEvent event, int pointerIndex)
boolean
onStartNestedScroll(View child, View target, int nestedScrollAxes)
void
void
void
void
void
void
void
removeDetachedView(View child, boolean animate)
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

SCROLL_STATE_DRAGGING

Added in 1.1.0-rc01
public static final int SCROLL_STATE_DRAGGING = 1

Indicates that the pager is currently being dragged by the user.

SCROLL_STATE_IDLE

Added in 1.1.0-rc01
public static final int SCROLL_STATE_IDLE = 0

Indicates that the pager 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.1.0-rc01
public static final int SCROLL_STATE_SETTLING = 2

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

Public constructors

ViewPager

Added in 1.1.0-rc01
public ViewPager(@NonNull Context context)

ViewPager

Added in 1.1.0-rc01
public ViewPager(@NonNull Context context, @Nullable AttributeSet attrs)

Public methods

addFocusables

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

We only want the current page that is being shown to be focusable.

addOnAdapterChangeListener

Added in 1.1.0-rc01
public void addOnAdapterChangeListener(
    @NonNull ViewPager.OnAdapterChangeListener listener
)

Add a listener that will be invoked whenever the adapter for this ViewPager changes.

Parameters
@NonNull ViewPager.OnAdapterChangeListener listener

listener to add

addOnPageChangeListener

Added in 1.1.0-rc01
public void addOnPageChangeListener(
    @NonNull ViewPager.OnPageChangeListener listener
)

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

Components that add a listener should take care to remove it when finished. Other components that take ownership of a view may call clearOnPageChangeListeners to remove all attached listeners.

Parameters
@NonNull ViewPager.OnPageChangeListener listener

listener to add

addTouchables

public void addTouchables(ArrayList<View> views)

We only want the current page that is being shown to be touchable.

addView

public void addView(View child, int index, ViewGroup.LayoutParams params)

arrowScroll

Added in 1.1.0-rc01
public boolean arrowScroll(int direction)

Handle scrolling in response to a left or right arrow click.

Parameters
int direction

The direction corresponding to the arrow key that was pressed. It should be either FOCUS_LEFT or FOCUS_RIGHT.

Returns
boolean

Whether the scrolling was handled successfully.

beginFakeDrag

Added in 1.1.0-rc01
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 ViewPager with the touch scrolling of another view, while still letting the ViewPager 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.

During a fake drag the ViewPager will ignore all touch events. If a real 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)

Check if this ViewPager can be scrolled horizontally in a certain direction.

Parameters
int direction

Negative to check scrolling left, positive to check scrolling right.

Returns
boolean

Whether this ViewPager can be scrolled in the specified direction. It will always return false if the specified direction is 0.

clearOnPageChangeListeners

Added in 1.1.0-rc01
public void clearOnPageChangeListeners()

Remove all listeners that are notified of any changes in scroll state or position.

computeScroll

public void computeScroll()

dispatchKeyEvent

public boolean dispatchKeyEvent(KeyEvent event)

dispatchPopulateAccessibilityEvent

public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event)

draw

public void draw(@NonNull Canvas canvas)

endFakeDrag

Added in 1.1.0-rc01
public void endFakeDrag()

End a fake drag of the pager.

executeKeyEvent

Added in 1.1.0-rc01
public boolean executeKeyEvent(@NonNull KeyEvent event)

You can call this function yourself to have the scroll view perform scrolling from a key event, just as if the event had been dispatched to it by the view hierarchy.

Parameters
@NonNull KeyEvent event

The key event to execute.

Returns
boolean

Return true if the event was handled, else false.

fakeDragBy

Added in 1.1.0-rc01
public void fakeDragBy(float xOffset)

Fake drag by an offset in pixels. You must have called beginFakeDrag first.

Parameters
float xOffset

Offset in pixels to drag by.

generateLayoutParams

public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs)

getAdapter

Added in 1.1.0-rc01
public @Nullable PagerAdapter getAdapter()

Retrieve the current adapter supplying pages.

Returns
@Nullable PagerAdapter

The currently registered PagerAdapter

getCurrentItem

Added in 1.1.0-rc01
public int getCurrentItem()

getOffscreenPageLimit

Added in 1.1.0-rc01
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 1.

Returns
int

How many pages will be kept offscreen on either side

getPageMargin

Added in 1.1.0-rc01
public int getPageMargin()

Return the margin between pages.

Returns
int

The size of the margin in pixels

isDragInGutterEnabled

Added in 1.1.0-rc01
public boolean isDragInGutterEnabled()
Returns
boolean

Whether dragging in the gutter (left and right edges) of the ViewPager is enabled.

isFakeDragging

Added in 1.1.0-rc01
public boolean isFakeDragging()

Returns true if a fake drag is in progress.

Returns
boolean

true if currently in a fake drag, false otherwise.

onInterceptTouchEvent

public boolean onInterceptTouchEvent(MotionEvent ev)

onRestoreInstanceState

Added in 1.1.0-rc01
public void onRestoreInstanceState(Parcelable state)

onSaveInstanceState

Added in 1.1.0-rc01
public @NonNull Parcelable onSaveInstanceState()

onTouchEvent

public boolean onTouchEvent(MotionEvent ev)

removeOnAdapterChangeListener

Added in 1.1.0-rc01
public void removeOnAdapterChangeListener(
    @NonNull ViewPager.OnAdapterChangeListener listener
)

Remove a listener that was previously added via addOnAdapterChangeListener.

Parameters
@NonNull ViewPager.OnAdapterChangeListener listener

listener to remove

removeOnPageChangeListener

Added in 1.1.0-rc01
public void removeOnPageChangeListener(
    @NonNull ViewPager.OnPageChangeListener listener
)

Remove a listener that was previously added via addOnPageChangeListener.

Parameters
@NonNull ViewPager.OnPageChangeListener listener

listener to remove

removeView

public void removeView(View view)

setAdapter

Added in 1.1.0-rc01
public void setAdapter(@Nullable PagerAdapter adapter)

Set a PagerAdapter that will supply views for this pager as needed.

Parameters
@Nullable PagerAdapter adapter

Adapter to use

setCurrentItem

Added in 1.1.0-rc01
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.

Parameters
int item

Item index to select

setCurrentItem

Added in 1.1.0-rc01
public void setCurrentItem(int item, boolean smoothScroll)

Set the currently selected page.

Parameters
int item

Item index to select

boolean smoothScroll

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

setDragInGutterEnabled

Added in 1.1.0-rc01
public void setDragInGutterEnabled(boolean enabled)

Set whether ViewPager should consume drag events if they are within the gutter (left and right edges) of the ViewPager. The default value false.

Parameters
boolean enabled

true if ViewPager should allow drag in gutter, false otherwise

setOffscreenPageLimit

Added in 1.1.0-rc01
public void setOffscreenPageLimit(int limit)

Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed.

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. This setting defaults to 1.

Parameters
int limit

How many pages will be kept offscreen in an idle state.

setOnPageChangeListener

Added in 1.1.0-rc01
Deprecated in 1.1.0-rc01
public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener)

Set a listener that will be invoked whenever the page changes or is incrementally scrolled. See OnPageChangeListener.

Parameters
ViewPager.OnPageChangeListener listener

Listener to set

setPageMargin

Added in 1.1.0-rc01
public void setPageMargin(int marginPixels)

Set the margin between pages.

Parameters
int marginPixels

Distance between adjacent pages in pixels

setPageMarginDrawable

Added in 1.1.0-rc01
public void setPageMarginDrawable(@Nullable Drawable d)

Set a drawable that will be used to fill the margin between pages.

Parameters
@Nullable Drawable d

Drawable to display between pages

setPageMarginDrawable

Added in 1.1.0-rc01
public void setPageMarginDrawable(@DrawableRes int resId)

Set a drawable that will be used to fill the margin between pages.

Parameters
@DrawableRes int resId

Resource ID of a drawable to display between pages

setPageTransformer

Added in 1.1.0-rc01
public void setPageTransformer(
    boolean reverseDrawingOrder,
    @Nullable ViewPager.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: By default, calling this method will cause contained pages to use LAYER_TYPE_HARDWARE. This layer type allows custom alpha transformations, but it will cause issues if any of your pages contain a android.view.SurfaceView and you have not called setZOrderOnTop to put that android.view.SurfaceView above your app content. To disable this behavior, call setPageTransformer and pass LAYER_TYPE_NONE for pageLayerType.

Parameters
boolean reverseDrawingOrder

true if the supplied PageTransformer requires page views to be drawn from last to first instead of first to last.

@Nullable ViewPager.PageTransformer transformer

PageTransformer that will modify each page's animation properties

setPageTransformer

Added in 1.1.0-rc01
public void setPageTransformer(
    boolean reverseDrawingOrder,
    @Nullable ViewPager.PageTransformer transformer,
    int pageLayerType
)

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.

Parameters
boolean reverseDrawingOrder

true if the supplied PageTransformer requires page views to be drawn from last to first instead of first to last.

@Nullable ViewPager.PageTransformer transformer

PageTransformer that will modify each page's animation properties

int pageLayerType

View layer type that should be used for ViewPager pages. It should be either LAYER_TYPE_HARDWARE, LAYER_TYPE_SOFTWARE, or LAYER_TYPE_NONE.

Protected methods

canScroll

Added in 1.1.0-rc01
protected boolean canScroll(@NonNull View v, boolean checkV, int dx, int x, int y)

Tests scrollability within child views of v given a delta of dx.

Parameters
@NonNull View v

View to test for horizontal scrollability

boolean checkV

Whether the view v passed should itself be checked for scrollability (true), or just its children (false).

int dx

Delta scrolled in pixels

int x

X coordinate of the active touch point

int y

Y coordinate of the active touch point

Returns
boolean

true if child views of v can be scrolled by delta of dx.

checkLayoutParams

protected boolean checkLayoutParams(ViewGroup.LayoutParams p)

drawableStateChanged

protected void drawableStateChanged()

generateDefaultLayoutParams

protected ViewGroup.LayoutParams generateDefaultLayoutParams()

getChildDrawingOrder

protected int getChildDrawingOrder(int childCount, int i)

onAttachedToWindow

protected void onAttachedToWindow()

onDetachedFromWindow

protected void onDetachedFromWindow()

onDraw

protected void onDraw(@NonNull Canvas canvas)

onLayout

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

onMeasure

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

onPageScrolled

Added in 1.1.0-rc01
@CallSuper
protected void onPageScrolled(int position, float offset, int offsetPixels)

This method will be invoked when the current page is scrolled, either as part of a programmatically initiated smooth scroll or a user initiated touch scroll. If you override this method you must call through to the superclass implementation (e.g. super.onPageScrolled(position, offset, offsetPixels)) before onPageScrolled returns.

Parameters
int position

Position index of the first page currently being displayed. Page position+1 will be visible if positionOffset is nonzero.

float offset

Value from [0, 1) indicating the offset from the page at position.

int offsetPixels

Value in pixels indicating the offset from position.

onRequestFocusInDescendants

protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect)

We only want the current page that is being shown to be focusable.

onSizeChanged

protected void onSizeChanged(int w, int h, int oldw, int oldh)

verifyDrawable

protected boolean verifyDrawable(@NonNull Drawable who)