ViewPager

open class ViewPager : ViewGroup
kotlin.Any
   ↳ android.view.View
   ↳ android.view.ViewGroup
   ↳ androidx.viewpager.widget.ViewPager

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

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

open

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

abstract

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

abstract

Callback interface for responding to adapter changes.

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

open

This is the persistent state that is saved by ViewPager.

open

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

Constants
static Int

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

static Int

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

static Int

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

Public constructors
<init>(@NonNull context: Context)

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

Public methods
open Unit
addView(child: View!, index: Int, params: LayoutParams!)

open Boolean

open Unit

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

open Unit
setPageMargin(marginPixels: Int)

Set the margin between pages.

open Int

open Unit

Remove a listener that was previously added via addOnAdapterChangeListener(OnAdapterChangeListener).

open Unit

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

open Unit

Remove a listener that was previously added via addOnPageChangeListener(OnPageChangeListener).

open Boolean
arrowScroll(direction: Int)

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

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

open Unit

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

open Unit
setPageMarginDrawable(@DrawableRes resId: Int)

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

open Parcelable!

open Unit
setAdapter(@Nullable adapter: PagerAdapter?)

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

open Boolean

Start a fake drag of the pager.

open Boolean

open Unit

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

open Unit

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

open PagerAdapter?

Retrieve the current adapter supplying pages.

open Boolean

Returns true if a fake drag is in progress.

open Unit

open Unit
removeView(view: View!)

open LayoutParams!

open Unit
setPageTransformer(reverseDrawingOrder: Boolean, @Nullable transformer: ViewPager.PageTransformer?)

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

open Unit
setPageTransformer(reverseDrawingOrder: Boolean, @Nullable transformer: ViewPager.PageTransformer?, pageLayerType: Int)

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

open Unit
draw(canvas: Canvas!)

open Unit

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

open Unit
addFocusables(views: ArrayList<View!>!, direction: Int, focusableMode: Int)

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

open Int

Return the margin between pages.

open Unit

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

open Unit
fakeDragBy(xOffset: Float)

Fake drag by an offset in pixels.

open Unit

Set the currently selected page.

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

Set the currently selected page.

open Boolean

open Boolean
executeKeyEvent(@NonNull event: KeyEvent)

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.

open Boolean

open Unit

End a fake drag of the pager.

open Boolean

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

open Unit

Protected methods
open Unit

open Int
getChildDrawingOrder(childCount: Int, i: Int)

open Unit

open Boolean

open Boolean

open Unit
onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int)

open Unit

open Boolean
onRequestFocusInDescendants(direction: Int, previouslyFocusedRect: Rect!)

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

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

open LayoutParams!

open Unit
onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int)

open Boolean
canScroll(v: View!, checkV: Boolean, dx: Int, x: Int, y: Int)

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

open LayoutParams!

open Unit
onDraw(canvas: Canvas!)

open Unit
onPageScrolled(position: Int, offset: Float, offsetPixels: Int)

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.

Constants

SCROLL_STATE_IDLE

static val SCROLL_STATE_IDLE: Int

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

Value: 0

SCROLL_STATE_DRAGGING

static val SCROLL_STATE_DRAGGING: Int

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

Value: 1

SCROLL_STATE_SETTLING

static val SCROLL_STATE_SETTLING: Int

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

Value: 2

Public constructors

<init>

ViewPager(@NonNull context: Context)

<init>

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

Public methods

addView

open fun addView(child: View!, index: Int, params: LayoutParams!): Unit

onTouchEvent

open fun onTouchEvent(ev: MotionEvent!): Boolean

addOnPageChangeListener

open fun addOnPageChangeListener(@NonNull listener: ViewPager.OnPageChangeListener): Unit

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
listener ViewPager.OnPageChangeListener: listener to add

setPageMargin

open fun setPageMargin(marginPixels: Int): Unit

Set the margin between pages.

Parameters
marginPixels Int: Distance between adjacent pages in pixels

getCurrentItem

open fun getCurrentItem(): Int

removeOnAdapterChangeListener

open fun removeOnAdapterChangeListener(@NonNull listener: ViewPager.OnAdapterChangeListener): Unit

Remove a listener that was previously added via addOnAdapterChangeListener(OnAdapterChangeListener).

Parameters
listener ViewPager.OnAdapterChangeListener: listener to remove

setOnPageChangeListener

open fun setOnPageChangeListener(listener: ViewPager.OnPageChangeListener!): Unit

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

Parameters
listener ViewPager.OnPageChangeListener!: Listener to set

removeOnPageChangeListener

open fun removeOnPageChangeListener(@NonNull listener: ViewPager.OnPageChangeListener): Unit

Remove a listener that was previously added via addOnPageChangeListener(OnPageChangeListener).

Parameters
listener ViewPager.OnPageChangeListener: listener to remove

arrowScroll

open fun arrowScroll(direction: Int): Boolean

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

Parameters
direction Int: The direction corresponding to the arrow key that was pressed. It should be either View#FOCUS_LEFT or View#FOCUS_RIGHT.
Return
Boolean: Whether the scrolling was handled successfully.

getOffscreenPageLimit

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

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

setPageMarginDrawable

open fun setPageMarginDrawable(@Nullable d: Drawable?): Unit

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

Parameters
d Drawable?: Drawable to display between pages

setPageMarginDrawable

open fun setPageMarginDrawable(@DrawableRes resId: Int): Unit

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

Parameters
resId Int: Resource ID of a drawable to display between pages

onSaveInstanceState

open fun onSaveInstanceState(): Parcelable!

setAdapter

open fun setAdapter(@Nullable adapter: PagerAdapter?): Unit

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

Parameters
adapter PagerAdapter?: Adapter to use

beginFakeDrag

open 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 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(float) 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.

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

dispatchKeyEvent

open fun dispatchKeyEvent(event: KeyEvent!): Boolean

addTouchables

open fun addTouchables(views: ArrayList<View!>!): Unit

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

setOffscreenPageLimit

open fun setOffscreenPageLimit(limit: Int): Unit

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
limit Int: How many pages will be kept offscreen in an idle state.

getAdapter

@Nullable open fun getAdapter(): PagerAdapter?

Retrieve the current adapter supplying pages.

Return
PagerAdapter?: The currently registered PagerAdapter

isFakeDragging

open fun isFakeDragging(): Boolean

Returns true if a fake drag is in progress.

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

computeScroll

open fun computeScroll(): Unit

removeView

open fun removeView(view: View!): Unit

generateLayoutParams

open fun generateLayoutParams(attrs: AttributeSet!): LayoutParams!

setPageTransformer

open fun setPageTransformer(reverseDrawingOrder: Boolean, @Nullable transformer: ViewPager.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: By default, calling this method will cause contained pages to use View#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 android.view.SurfaceView#setZOrderOnTop(boolean) to put that android.view.SurfaceView above your app content. To disable this behavior, call setPageTransformer(boolean,PageTransformer,int) and pass View#LAYER_TYPE_NONE for pageLayerType.

Parameters
reverseDrawingOrder Boolean: true if the supplied PageTransformer requires page views to be drawn from last to first instead of first to last.
transformer Boolean: PageTransformer that will modify each page's animation properties

setPageTransformer

open fun setPageTransformer(reverseDrawingOrder: Boolean, @Nullable transformer: ViewPager.PageTransformer?, pageLayerType: Int): 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.

Parameters
reverseDrawingOrder Boolean: true if the supplied PageTransformer requires page views to be drawn from last to first instead of first to last.
transformer Boolean: PageTransformer that will modify each page's animation properties
pageLayerType Boolean: View layer type that should be used for ViewPager pages. It should be either View#LAYER_TYPE_HARDWARE, View#LAYER_TYPE_SOFTWARE, or View#LAYER_TYPE_NONE.

draw

open fun draw(canvas: Canvas!): Unit

clearOnPageChangeListeners

open fun clearOnPageChangeListeners(): Unit

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

addFocusables

open fun addFocusables(views: ArrayList<View!>!, direction: Int, focusableMode: Int): Unit

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

getPageMargin

open fun getPageMargin(): Int

Return the margin between pages.

Return
Int: The size of the margin in pixels

addOnAdapterChangeListener

open fun addOnAdapterChangeListener(@NonNull listener: ViewPager.OnAdapterChangeListener): Unit

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

Parameters
listener ViewPager.OnAdapterChangeListener: listener to add

fakeDragBy

open fun fakeDragBy(xOffset: Float): Unit

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

Parameters
xOffset Float: Offset in pixels to drag by.

setCurrentItem

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

Parameters
item Int: Item index to select

setCurrentItem

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

Set the currently selected page.

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

dispatchPopulateAccessibilityEvent

open fun dispatchPopulateAccessibilityEvent(event: AccessibilityEvent!): Boolean

executeKeyEvent

open fun executeKeyEvent(@NonNull event: KeyEvent): 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.

Parameters
event KeyEvent: The key event to execute.
Return
Boolean: Return true if the event was handled, else false.

onInterceptTouchEvent

open fun onInterceptTouchEvent(ev: MotionEvent!): Boolean

endFakeDrag

open fun endFakeDrag(): Unit

End a fake drag of the pager.

canScrollHorizontally

open fun canScrollHorizontally(direction: Int): Boolean

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

Parameters
direction Int: Negative to check scrolling left, positive to check scrolling right.
Return
Boolean: Whether this ViewPager can be scrolled in the specified direction. It will always return false if the specified direction is 0.

onRestoreInstanceState

open fun onRestoreInstanceState(state: Parcelable!): Unit

Protected methods

onAttachedToWindow

protected open fun onAttachedToWindow(): Unit

getChildDrawingOrder

protected open fun getChildDrawingOrder(childCount: Int, i: Int): Int

drawableStateChanged

protected open fun drawableStateChanged(): Unit

verifyDrawable

protected open fun verifyDrawable(who: Drawable!): Boolean

checkLayoutParams

protected open fun checkLayoutParams(p: LayoutParams!): Boolean

onSizeChanged

protected open fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int): Unit

onDetachedFromWindow

protected open fun onDetachedFromWindow(): Unit

onRequestFocusInDescendants

protected open fun onRequestFocusInDescendants(direction: Int, previouslyFocusedRect: Rect!): Boolean

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

onLayout

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

generateLayoutParams

protected open fun generateLayoutParams(p: LayoutParams!): LayoutParams!

onMeasure

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

canScroll

protected open fun canScroll(v: View!, checkV: Boolean, dx: Int, x: Int, y: Int): Boolean

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

Parameters
v View!: View to test for horizontal scrollability
checkV View!: Whether the view v passed should itself be checked for scrollability (true), or just its children (false).
dx View!: Delta scrolled in pixels
x View!: X coordinate of the active touch point
y View!: Y coordinate of the active touch point
Return
Boolean: true if child views of v can be scrolled by delta of dx.

generateDefaultLayoutParams

protected open fun generateDefaultLayoutParams(): LayoutParams!

onDraw

protected open fun onDraw(canvas: Canvas!): Unit

onPageScrolled

@CallSuper protected open fun onPageScrolled(position: Int, offset: Float, offsetPixels: Int): Unit

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
position Int: Position index of the first page currently being displayed. Page position+1 will be visible if positionOffset is nonzero.
offset Int: Value from [0, 1) indicating the offset from the page at position.
offsetPixels Int: Value in pixels indicating the offset from position.