Most visited

Recently visited

ViewPager

public class ViewPager
extends ViewGroup

java.lang.Object
   ↳ android.view.View
     ↳ android.view.ViewGroup
       ↳ android.support.v4.view.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 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 and FragmentStatePagerAdapter; each of these classes have simple code showing how to build a full user interface with them.

Views which are annotated with the ViewPager.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:

 <android.support.v4.view.ViewPager
     android:layout_width="match_parent"
     android:layout_height="match_parent">

     <android.support.v4.view.PagerTitleStrip
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_gravity="top" />

 </android.support.v4.view.ViewPager>
 

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

Below is a more complicated example of ViewPager, using it in conjunction 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

@interface ViewPager.DecorView

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

class ViewPager.LayoutParams

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

interface ViewPager.OnAdapterChangeListener

Callback interface for responding to adapter changes. 

interface ViewPager.OnPageChangeListener

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

interface ViewPager.PageTransformer

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

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. 

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.

Inherited constants

From class android.view.ViewGroup
From class android.view.View

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 addOnAdapterChangeListener(ViewPager.OnAdapterChangeListener listener)

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

void addOnPageChangeListener(ViewPager.OnPageChangeListener listener)

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

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.

boolean canScrollHorizontally(int direction)

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

void clearOnPageChangeListeners()

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

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 removeOnAdapterChangeListener(ViewPager.OnAdapterChangeListener listener)

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

void removeOnPageChangeListener(ViewPager.OnPageChangeListener listener)

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

void removeView(View view)

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

void setAdapter(PagerAdapter adapter)

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

This method is deprecated. Use addOnPageChangeListener(OnPageChangeListener) and removeOnPageChangeListener(OnPageChangeListener) instead.

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.

void setPageTransformer(boolean reverseDrawingOrder, ViewPager.PageTransformer transformer)

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

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.

int getChildDrawingOrder(int childCount, int i)

Returns the index of the child to draw for this iteration.

void onAttachedToWindow()

This is called when the view is attached to a window.

void onDetachedFromWindow()

This is called when the view is detached from 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.

Inherited methods

From class android.view.ViewGroup
From class android.view.View
From class java.lang.Object
From interface android.view.ViewParent
From interface android.view.ViewManager
From interface android.graphics.drawable.Drawable.Callback
From interface android.view.KeyEvent.Callback
From interface android.view.accessibility.AccessibilityEventSource

Constants

SCROLL_STATE_DRAGGING

int SCROLL_STATE_DRAGGING

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

Constant Value: 1 (0x00000001)

SCROLL_STATE_IDLE

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)

SCROLL_STATE_SETTLING

int SCROLL_STATE_SETTLING

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

Constant Value: 2 (0x00000002)

Public constructors

ViewPager

ViewPager (Context context)

Parameters
context Context

ViewPager

ViewPager (Context context, 
                AttributeSet attrs)

Parameters
context Context
attrs AttributeSet

Public methods

addFocusables

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

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

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

addOnAdapterChangeListener

void addOnAdapterChangeListener (ViewPager.OnAdapterChangeListener listener)

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

Parameters
listener ViewPager.OnAdapterChangeListener: listener to add

addOnPageChangeListener

void addOnPageChangeListener (ViewPager.OnPageChangeListener listener)

Add a listener that will be invoked whenever the page changes or is incrementally scrolled. See ViewPager.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

addTouchables

void addTouchables (ArrayList<View> views)

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

Parameters
views ArrayList: Touchable views found so far

addView

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 View: the child view to add
index int: the position at which to add the child or -1 to add last
params ViewGroup.LayoutParams: the layout parameters to set on the child

arrowScroll

boolean arrowScroll (int direction)

Parameters
direction int
Returns
boolean

beginFakeDrag

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
boolean true if the fake drag began successfully, false if it could not be started.

See also:

canScrollHorizontally

boolean canScrollHorizontally (int direction)

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

Parameters
direction int: Negative to check scrolling left, positive to check scrolling right.
Returns
boolean true if this view can be scrolled in the specified direction, false otherwise.

clearOnPageChangeListeners

void clearOnPageChangeListeners ()

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

computeScroll

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.

dispatchKeyEvent

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 KeyEvent: The key event to be dispatched.
Returns
boolean True if the event was handled, false otherwise.

dispatchPopulateAccessibilityEvent

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 AccessibilityEvent: The event.
Returns
boolean True if the event population was completed.

draw

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 Canvas: The Canvas to which the View is rendered.

endFakeDrag

void endFakeDrag ()

End a fake drag of the pager.

See also:

executeKeyEvent

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

fakeDragBy

void fakeDragBy (float xOffset)

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

Parameters
xOffset float: Offset in pixels to drag by.

See also:

generateLayoutParams

ViewGroup.LayoutParams generateLayoutParams (AttributeSet attrs)

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

Parameters
attrs AttributeSet: the attributes to build the layout parameters from
Returns
ViewGroup.LayoutParams an instance of ViewGroup.LayoutParams or one of its descendants

getAdapter

PagerAdapter getAdapter ()

Retrieve the current adapter supplying pages.

Returns
PagerAdapter The currently registered PagerAdapter

getCurrentItem

int getCurrentItem ()

Returns
int

getOffscreenPageLimit

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

See also:

getPageMargin

int getPageMargin ()

Return the margin between pages.

Returns
int The size of the margin in pixels

isFakeDragging

boolean isFakeDragging ()

Returns true if a fake drag is in progress.

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

See also:

onInterceptTouchEvent

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 MotionEvent: The motion event being dispatched down the hierarchy.
Returns
boolean 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.

onRestoreInstanceState

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 Parcelable: The frozen state that had previously been returned by onSaveInstanceState().

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

onTouchEvent

boolean onTouchEvent (MotionEvent ev)

Implement this method to handle touch screen motion events.

If this method is used to detect click actions, it is recommended that the actions be performed by implementing and calling performClick(). This will ensure consistent system behavior, including:

  • obeying click sound preferences
  • dispatching OnClickListener calls
  • handling ACTION_CLICK when accessibility features are enabled

Parameters
ev MotionEvent: The motion event.
Returns
boolean True if the event was handled, false otherwise.

removeOnAdapterChangeListener

void removeOnAdapterChangeListener (ViewPager.OnAdapterChangeListener listener)

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

Parameters
listener ViewPager.OnAdapterChangeListener: listener to remove

removeOnPageChangeListener

void removeOnPageChangeListener (ViewPager.OnPageChangeListener listener)

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

Parameters
listener ViewPager.OnPageChangeListener: listener to remove

removeView

void removeView (View view)

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

Parameters
view View

setAdapter

void setAdapter (PagerAdapter adapter)

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

Parameters
adapter PagerAdapter: Adapter to use

setCurrentItem

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

setCurrentItem

void setCurrentItem (int item, 
                boolean smoothScroll)

Set the currently selected page.

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

setOffscreenPageLimit

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

setOnPageChangeListener

void setOnPageChangeListener (ViewPager.OnPageChangeListener listener)

This method is deprecated.
Use addOnPageChangeListener(OnPageChangeListener) and removeOnPageChangeListener(OnPageChangeListener) instead.

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

Parameters
listener ViewPager.OnPageChangeListener: Listener to set

setPageMargin

void setPageMargin (int marginPixels)

Set the margin between pages.

Parameters
marginPixels int: Distance between adjacent pages in pixels

See also:

setPageMarginDrawable

void setPageMarginDrawable (int resId)

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

setPageMarginDrawable

void setPageMarginDrawable (Drawable d)

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

Parameters
d Drawable: Drawable to display between pages

setPageTransformer

void setPageTransformer (boolean reverseDrawingOrder, 
                ViewPager.PageTransformer transformer)

Set a ViewPager.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 look and feel.

Note: Prior to Android 3.0 the property animation APIs did not exist. As a result, setting a PageTransformer prior to Android 3.0 (API 11) will have no effect.

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

Protected methods

canScroll

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: View to test for horizontal scrollability
checkV boolean: Whether the view v passed should itself be checked for scrollability (true), or just its children (false).
dx int: Delta scrolled in pixels
x int: X coordinate of the active touch point
y int: Y coordinate of the active touch point
Returns
boolean true if child views of v can be scrolled by delta of dx.

checkLayoutParams

boolean checkLayoutParams (ViewGroup.LayoutParams p)

Parameters
p ViewGroup.LayoutParams
Returns
boolean

drawableStateChanged

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.

If the View has a StateListAnimator, it will also be called to run necessary state change animations.

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

generateDefaultLayoutParams

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
ViewGroup.LayoutParams a set of default layout parameters or null

generateLayoutParams

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 ViewGroup.LayoutParams: The layout parameters to convert into a suitable set of layout parameters for this ViewGroup.
Returns
ViewGroup.LayoutParams an instance of ViewGroup.LayoutParams or one of its descendants

getChildDrawingOrder

int getChildDrawingOrder (int childCount, 
                int i)

Returns the index of the child to draw for this iteration. Override this if you want to change the drawing order of children. By default, it returns i.

NOTE: In order for this method to be called, you must enable child ordering first by calling setChildrenDrawingOrderEnabled(boolean).

Parameters
childCount int
i int: The current iteration.
Returns
int The index of the child to draw this iteration.

onAttachedToWindow

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

onDetachedFromWindow

void onDetachedFromWindow ()

This is called when the view is detached from a window. At this point it no longer has a surface for drawing.

onDraw

void onDraw (Canvas canvas)

Implement this to do your drawing.

Parameters
canvas Canvas: the canvas on which the background will be drawn

onLayout

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 boolean: This is a new size or position for this view
l int: Left position, relative to parent
t int: Top position, relative to parent
r int: Right position, relative to parent
b int: Bottom position, relative to parent

onMeasure

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 overridden 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 int: horizontal space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.
heightMeasureSpec int: vertical space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.

onPageScrolled

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

onRequestFocusInDescendants

boolean onRequestFocusInDescendants (int direction, 
                Rect previouslyFocusedRect)

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

Parameters
direction int: One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
previouslyFocusedRect Rect: 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
boolean Whether focus was taken.

onSizeChanged

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 int: Current width of this view.
h int: Current height of this view.
oldw int: Old width of this view.
oldh int: Old height of this view.

verifyDrawable

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 Drawable: 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 boolean If true than the Drawable is being displayed in the view; else false and it is not allowed to animate.

Hooray!