to top
Android APIs
public class

ViewPager

extends ViewGroup
java.lang.Object
   ↳ android.view.View
     ↳ android.view.ViewGroup
       ↳ android.support.v4.view.ViewPager

Class Overview

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.

Note this class is currently under early design and development. The API will likely change in later updates of the compatibility library, requiring changes to the source code of apps when they are compiled against the newer version.

ViewPager is most often used in conjunction with 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 FragmentPagerAdapter, FragmentStatePagerAdapter, FragmentPagerAdapter, and FragmentStatePagerAdapter; each of these classes have simple code showing how to build a full user interface with them.

Here is a more complicated example of ViewPager, using it in conjuction with ActionBar tabs. You can find other examples of using ViewPager in the API 4+ Support Demos and API 13+ Support Demos sample code.

public class ActionBarTabsPager extends Activity {
    ViewPager mViewPager;
    TabsAdapter mTabsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mViewPager = new ViewPager(this);
        mViewPager.setId(R.id.pager);
        setContentView(mViewPager);

        final ActionBar bar = getActionBar();
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);

        mTabsAdapter = new TabsAdapter(this, mViewPager);
        mTabsAdapter.addTab(bar.newTab().setText("Simple"),
                CountingFragment.class, null);
        mTabsAdapter.addTab(bar.newTab().setText("List"),
                FragmentPagerSupport.ArrayListFragment.class, null);
        mTabsAdapter.addTab(bar.newTab().setText("Cursor"),
                CursorFragment.class, null);

        if (savedInstanceState != null) {
            bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
    }

    /**
     * This is a helper class that implements the management of tabs and all
     * details of connecting a ViewPager with associated TabHost.  It relies on a
     * trick.  Normally a tab host has a simple API for supplying a View or
     * Intent that each tab will show.  This is not sufficient for switching
     * between pages.  So instead we make the content part of the tab host
     * 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
     * view to show as the tab content.  It listens to changes in tabs, and takes
     * care of switch to the correct paged in the ViewPager whenever the selected
     * tab changes.
     */
    public static class TabsAdapter extends FragmentPagerAdapter
            implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
        private final Context mContext;
        private final ActionBar mActionBar;
        private final ViewPager mViewPager;
        private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

        static final class TabInfo {
            private final Class<?> clss;
            private final Bundle args;

            TabInfo(Class<?> _class, Bundle _args) {
                clss = _class;
                args = _args;
            }
        }

        public TabsAdapter(Activity activity, ViewPager pager) {
            super(activity.getFragmentManager());
            mContext = activity;
            mActionBar = activity.getActionBar();
            mViewPager = pager;
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
        }

        public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
            TabInfo info = new TabInfo(clss, args);
            tab.setTag(info);
            tab.setTabListener(this);
            mTabs.add(info);
            mActionBar.addTab(tab);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mTabs.size();
        }

        @Override
        public Fragment getItem(int position) {
            TabInfo info = mTabs.get(position);
            return Fragment.instantiate(mContext, info.clss.getName(), info.args);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            mActionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            Object tag = tab.getTag();
            for (int i=0; i<mTabs.size(); i++) {
                if (mTabs.get(i) == tag) {
                    mViewPager.setCurrentItem(i);
                }
            }
        }

        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        }

        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
        }
    }
}

Summary

Nested Classes
class ViewPager.LayoutParams Layout parameters that should be supplied for views added to a ViewPager. 
interface ViewPager.OnPageChangeListener Callback interface for responding to changing state of the selected page. 
class ViewPager.SavedState This is the persistent state that is saved by ViewPager. 
class ViewPager.SimpleOnPageChangeListener Simple implementation of the ViewPager.OnPageChangeListener interface with stub implementations of each method. 
[Expand]
Inherited XML Attributes
From class android.view.ViewGroup
From class android.view.View
Constants
int SCROLL_STATE_DRAGGING Indicates that the pager is currently being dragged by the user.
int SCROLL_STATE_IDLE Indicates that the pager is in an idle, settled state.
int SCROLL_STATE_SETTLING Indicates that the pager is in the process of settling to a final position.
[Expand]
Inherited Constants
From class android.view.ViewGroup
From class android.view.View
[Expand]
Inherited Fields
From class android.view.View
Public Constructors
ViewPager(Context context)
ViewPager(Context context, AttributeSet attrs)
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 addTouchables(ArrayList<View> views)
We only want the current page that is being shown to be touchable.
void addView(View child, int index, ViewGroup.LayoutParams params)
Adds a child view with the specified layout parameters.
boolean arrowScroll(int direction)
boolean beginFakeDrag()
Start a fake drag of the pager.
void computeScroll()
Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary.
boolean dispatchKeyEvent(KeyEvent event)
Dispatch a key event to the next view on the focus path.
boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event)
Dispatches an AccessibilityEvent to the View first and then to its children for adding their text content to the event.
void draw(Canvas canvas)
Manually render this view (and all of its children) to the given Canvas.
void endFakeDrag()
End a fake drag of the pager.
boolean executeKeyEvent(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.
void fakeDragBy(float xOffset)
Fake drag by an offset in pixels.
ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs)
Returns a new set of layout parameters based on the supplied attributes set.
PagerAdapter getAdapter()
Retrieve the current adapter supplying pages.
int getCurrentItem()
int getOffscreenPageLimit()
Returns the number of pages that will be retained to either side of the current page in the view hierarchy in an idle state.
int getPageMargin()
Return the margin between pages.
boolean isFakeDragging()
Returns true if a fake drag is in progress.
boolean onInterceptTouchEvent(MotionEvent ev)
Implement this method to intercept all touch screen motion events.
void onRestoreInstanceState(Parcelable state)
Hook allowing a view to re-apply a representation of its internal state that had previously been generated by onSaveInstanceState().
Parcelable onSaveInstanceState()
Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state.
boolean onTouchEvent(MotionEvent ev)
Implement this method to handle touch screen motion events.
void setAdapter(PagerAdapter adapter)
Set a PagerAdapter that will supply views for this pager as needed.
void setCurrentItem(int item, boolean smoothScroll)
Set the currently selected page.
void setCurrentItem(int item)
Set the currently selected page.
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.
void setOnPageChangeListener(ViewPager.OnPageChangeListener listener)
Set a listener that will be invoked whenever the page changes or is incrementally scrolled.
void setPageMargin(int marginPixels)
Set the margin between pages.
void setPageMarginDrawable(int resId)
Set a drawable that will be used to fill the margin between pages.
void setPageMarginDrawable(Drawable d)
Set a drawable that will be used to fill the margin between pages.
Protected Methods
boolean canScroll(View v, boolean checkV, int dx, int x, int y)
Tests scrollability within child views of v given a delta of dx.
boolean checkLayoutParams(ViewGroup.LayoutParams p)
void drawableStateChanged()
This function is called whenever the state of the view changes in such a way that it impacts the state of drawables being shown.
ViewGroup.LayoutParams generateDefaultLayoutParams()
Returns a set of default layout parameters.
ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p)
Returns a safe set of layout parameters based on the supplied layout params.
void onAttachedToWindow()
This is called when the view is attached to a window.
void onDraw(Canvas canvas)
Implement this to do your drawing.
void onLayout(boolean changed, int l, int t, int r, int b)
Called from layout when this view should assign a size and position to each of its children.
void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height.

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.
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)
This is called during layout when the size of this view has changed.
boolean verifyDrawable(Drawable who)
If your view subclass is displaying its own Drawable objects, it should override this function and return true for any Drawable it is displaying.
[Expand]
Inherited Methods
From class android.view.ViewGroup
From class android.view.View
From class java.lang.Object
From interface android.graphics.drawable.Drawable.Callback
From interface android.view.KeyEvent.Callback
From interface android.view.ViewManager
From interface android.view.ViewParent
From interface android.view.accessibility.AccessibilityEventSource

Constants

public static final int SCROLL_STATE_DRAGGING

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

Constant Value: 1 (0x00000001)

public static final int SCROLL_STATE_IDLE

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

Constant Value: 0 (0x00000000)

public static final int SCROLL_STATE_SETTLING

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

Constant Value: 2 (0x00000002)

Public Constructors

public ViewPager (Context context)

public ViewPager (Context context, AttributeSet attrs)

Public Methods

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

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

Parameters
views Focusable views found so far or null if all we are interested is the number of focusables.
direction The direction of the focus.
focusableMode The type of focusables to be added.

public void addTouchables (ArrayList<View> views)

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

Parameters
views Touchable views found so far

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

Adds a child view with the specified layout parameters.

Note: do not invoke this method from draw(android.graphics.Canvas), onDraw(android.graphics.Canvas), dispatchDraw(android.graphics.Canvas) or any related method.

Parameters
child the child view to add
index the position at which to add the child
params the layout parameters to set on the child

public boolean arrowScroll (int direction)

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

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

public void computeScroll ()

Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary. This will typically be done if the child is animating a scroll using a Scroller object.

public boolean dispatchKeyEvent (KeyEvent event)

Dispatch a key event to the next view on the focus path. This path runs from the top of the view tree down to the currently focused view. If this view has focus, it will dispatch to itself. Otherwise it will dispatch the next node down the focus path. This method also fires any key listeners.

Parameters
event The key event to be dispatched.
Returns
  • True if the event was handled, false otherwise.

public boolean dispatchPopulateAccessibilityEvent (AccessibilityEvent event)

Dispatches an AccessibilityEvent to the View first and then to its children for adding their text content to the event. Note that the event text is populated in a separate dispatch path since we add to the event not only the text of the source but also the text of all its descendants. A typical implementation will call onPopulateAccessibilityEvent(AccessibilityEvent) on the this view and then call the dispatchPopulateAccessibilityEvent(AccessibilityEvent) on each child. Override this method if custom population of the event text content is required.

If an View.AccessibilityDelegate has been specified via calling setAccessibilityDelegate(AccessibilityDelegate) its dispatchPopulateAccessibilityEvent(View, AccessibilityEvent) is responsible for handling this call.

Note: Accessibility events of certain types are not dispatched for populating the event text via this method. For details refer to AccessibilityEvent.

Parameters
event The event.
Returns
  • True if the event population was completed.

public void draw (Canvas canvas)

Manually render this view (and all of its children) to the given Canvas. The view must have already done a full layout before this function is called. When implementing a view, implement onDraw(android.graphics.Canvas) instead of overriding this method. If you do need to override this method, call the superclass version.

Parameters
canvas The Canvas to which the View is rendered.

public void endFakeDrag ()

End a fake drag of the pager.

public boolean executeKeyEvent (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
event The key event to execute.
Returns
  • Return true if the event was handled, else false.

public void fakeDragBy (float xOffset)

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

Parameters
xOffset Offset in pixels to drag by.

public ViewGroup.LayoutParams generateLayoutParams (AttributeSet attrs)

Returns a new set of layout parameters based on the supplied attributes set.

Parameters
attrs the attributes to build the layout parameters from
Returns

public PagerAdapter getAdapter ()

Retrieve the current adapter supplying pages.

Returns
  • The currently registered PagerAdapter

public int getCurrentItem ()

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
  • How many pages will be kept offscreen on either side

public int getPageMargin ()

Return the margin between pages.

Returns
  • The size of the margin in pixels

public boolean isFakeDragging ()

Returns true if a fake drag is in progress.

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

public boolean onInterceptTouchEvent (MotionEvent ev)

Implement this method to intercept all touch screen motion events. This allows you to watch events as they are dispatched to your children, and take ownership of the current gesture at any point.

Using this function takes some care, as it has a fairly complicated interaction with View.onTouchEvent(MotionEvent), and using it requires implementing that method as well as this one in the correct way. Events will be received in the following order:

  1. You will receive the down event here.
  2. The down event will be handled either by a child of this view group, or given to your own onTouchEvent() method to handle; this means you should implement onTouchEvent() to return true, so you will continue to see the rest of the gesture (instead of looking for a parent view to handle it). Also, by returning true from onTouchEvent(), you will not receive any following events in onInterceptTouchEvent() and all touch processing must happen in onTouchEvent() like normal.
  3. For as long as you return false from this function, each following event (up to and including the final up) will be delivered first here and then to the target's onTouchEvent().
  4. If you return true from here, you will not receive any following events: the target view will receive the same event but with the action ACTION_CANCEL, and all further events will be delivered to your onTouchEvent() method and no longer appear here.

Parameters
ev The motion event being dispatched down the hierarchy.
Returns
  • Return true to steal motion events from the children and have them dispatched to this ViewGroup through onTouchEvent(). The current target will receive an ACTION_CANCEL event, and no further messages will be delivered here.

public void onRestoreInstanceState (Parcelable state)

Hook allowing a view to re-apply a representation of its internal state that had previously been generated by onSaveInstanceState(). This function will never be called with a null state.

Parameters
state The frozen state that had previously been returned by onSaveInstanceState().

public Parcelable onSaveInstanceState ()

Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

Some examples of things you may store here: the current cursor position in a text view (but usually not the text itself since that is stored in a content provider or other persistent storage), the currently selected item in a list view.

Returns
  • Returns a Parcelable object containing the view's current dynamic state, or null if there is nothing interesting to save. The default implementation returns null.

public boolean onTouchEvent (MotionEvent ev)

Implement this method to handle touch screen motion events.

Parameters
ev The motion event.
Returns
  • True if the event was handled, false otherwise.

public void setAdapter (PagerAdapter adapter)

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

Parameters
adapter Adapter to use

public void setCurrentItem (int item, boolean smoothScroll)

Set the currently selected page.

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

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
item Item index to select

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

public void setOnPageChangeListener (ViewPager.OnPageChangeListener listener)

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

Parameters
listener Listener to set

public void setPageMargin (int marginPixels)

Set the margin between pages.

Parameters
marginPixels Distance between adjacent pages in pixels

public void setPageMarginDrawable (int resId)

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

Parameters
resId Resource ID of a drawable to display between pages

public void setPageMarginDrawable (Drawable d)

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

Parameters
d Drawable to display between pages

Protected Methods

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

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

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

protected boolean checkLayoutParams (ViewGroup.LayoutParams p)

protected void drawableStateChanged ()

This function is called whenever the state of the view changes in such a way that it impacts the state of drawables being shown.

Be sure to call through to the superclass when overriding this function.

protected ViewGroup.LayoutParams generateDefaultLayoutParams ()

Returns a set of default layout parameters. These parameters are requested when the View passed to addView(View) has no layout parameters already set. If null is returned, an exception is thrown from addView.

Returns
  • a set of default layout parameters or null

protected ViewGroup.LayoutParams generateLayoutParams (ViewGroup.LayoutParams p)

Returns a safe set of layout parameters based on the supplied layout params. When a ViewGroup is passed a View whose layout params do not pass the test of checkLayoutParams(android.view.ViewGroup.LayoutParams), this method is invoked. This method should return a new set of layout params suitable for this ViewGroup, possibly by copying the appropriate attributes from the specified set of layout params.

Parameters
p The layout parameters to convert into a suitable set of layout parameters for this ViewGroup.
Returns

protected void onAttachedToWindow ()

This is called when the view is attached to a window. At this point it has a Surface and will start drawing. Note that this function is guaranteed to be called before onDraw(android.graphics.Canvas), however it may be called any time before the first onDraw -- including before or after onMeasure(int, int).

protected void onDraw (Canvas canvas)

Implement this to do your drawing.

Parameters
canvas the canvas on which the background will be drawn

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

Called from layout when this view should assign a size and position to each of its children. Derived classes with children should override this method and call layout on each of their children.

Parameters
changed This is a new size or position for this view
l Left position, relative to parent
t Top position, relative to parent
r Right position, relative to parent
b Bottom position, relative to parent

protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height. This method is invoked by measure(int, int) and should be overriden by subclasses to provide accurate and efficient measurement of their contents.

CONTRACT: When overriding this method, you must call setMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger an IllegalStateException, thrown by measure(int, int). Calling the superclass' onMeasure(int, int) is a valid use.

The base class implementation of measure defaults to the background size, unless a larger size is allowed by the MeasureSpec. Subclasses should override onMeasure(int, int) to provide better measurements of their content.

If this method is overridden, it is the subclass's responsibility to make sure the measured height and width are at least the view's minimum height and width (getSuggestedMinimumHeight() and getSuggestedMinimumWidth()).

Parameters
widthMeasureSpec horizontal space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.
heightMeasureSpec vertical space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.

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

protected boolean onRequestFocusInDescendants (int direction, Rect previouslyFocusedRect)

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

Parameters
direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
previouslyFocusedRect The rectangle (in this View's coordinate system) to give a finer grained hint about where focus is coming from. May be null if there is no hint.
Returns
  • Whether focus was taken.

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

This is called during layout when the size of this view has changed. If you were just added to the view hierarchy, you're called with the old values of 0.

Parameters
w Current width of this view.
h Current height of this view.
oldw Old width of this view.
oldh Old height of this view.

protected boolean verifyDrawable (Drawable who)

If your view subclass is displaying its own Drawable objects, it should override this function and return true for any Drawable it is displaying. This allows animations for those drawables to be scheduled.

Be sure to call through to the super class when overriding this function.

Parameters
who The Drawable to verify. Return true if it is one you are displaying, else return the result of calling through to the super class.
Returns
  • boolean If true than the Drawable is being displayed in the view; else false and it is not allowed to animate.