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.
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
and
FragmentStatePagerAdapter
; each of these
classes have simple code showing how to build a full user interface
with them.
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) { } } }
Nested Classes | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
|
ViewPager.LayoutParams | Layout parameters that should be supplied for views added to a ViewPager. | |||||||||
|
ViewPager.OnPageChangeListener | Callback interface for responding to changing state of the selected page. | |||||||||
|
ViewPager.PageTransformer | A PageTransformer is invoked whenever a visible/attached page is scrolled. | |||||||||
|
ViewPager.SavedState | This is the persistent state that is saved by ViewPager. | |||||||||
|
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 | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
|
|
||||||||||
|
|
Public Methods | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
|
We only want the current page that is being shown to be focusable.
|
||||||||||
|
We only want the current page that is being shown to be touchable.
|
||||||||||
|
Adds a child view with the specified layout parameters.
|
||||||||||
|
|
||||||||||
|
Start a fake drag of the pager.
|
||||||||||
|
Check if this view can be scrolled horizontally in a certain direction.
|
||||||||||
|
Called by a parent to request that a child update its values for mScrollX
and mScrollY if necessary.
|
||||||||||
|
Dispatch a key event to the next view on the focus path.
|
||||||||||
|
Dispatches an
AccessibilityEvent
to the
View
first and then
to its children for adding their text content to the event.
|
||||||||||
|
Manually render this view (and all of its children) to the given Canvas.
|
||||||||||
|
End a fake drag of the pager.
|
||||||||||
|
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.
|
||||||||||
|
Fake drag by an offset in pixels.
|
||||||||||
|
Returns a new set of layout parameters based on the supplied attributes set.
|
||||||||||
|
Retrieve the current adapter supplying pages.
|
||||||||||
|
|
||||||||||
|
Returns the number of pages that will be retained to either side of the
current page in the view hierarchy in an idle state.
|
||||||||||
|
Return the margin between pages.
|
||||||||||
|
Returns true if a fake drag is in progress.
|
||||||||||
|
Implement this method to intercept all touch screen motion events.
|
||||||||||
|
Hook allowing a view to re-apply a representation of its internal state that had previously
been generated by
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.
|
||||||||||
|
Implement this method to handle touch screen motion events.
|
||||||||||
|
Note:
do not invoke this method from
|
||||||||||
|
Set a PagerAdapter that will supply views for this pager as needed.
|
||||||||||
|
Set the currently selected page.
|
||||||||||
|
Set the currently selected page.
|
||||||||||
|
Set the number of pages that should be retained to either side of the
current page in the view hierarchy in an idle state.
|
||||||||||
|
Set a listener that will be invoked whenever the page changes or is incrementally
scrolled.
|
||||||||||
|
Set the margin between pages.
|
||||||||||
|
Set a drawable that will be used to fill the margin between pages.
|
||||||||||
|
Set a drawable that will be used to fill the margin between pages.
|
||||||||||
|
Set a
ViewPager.PageTransformer
that will be called for each attached page whenever
the scroll position is changed.
|
Protected Methods | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
|
Tests scrollability within child views of v given a delta of dx.
|
||||||||||
|
|
||||||||||
|
This function is called whenever the state of the view changes in such
a way that it impacts the state of drawables being shown.
|
||||||||||
|
Returns a set of default layout parameters.
|
||||||||||
|
Returns a safe set of layout parameters based on the supplied layout params.
|
||||||||||
|
Returns the index of the child to draw for this iteration.
|
||||||||||
|
This is called when the view is attached to a window.
|
||||||||||
|
This is called when the view is detached from a window.
|
||||||||||
|
Implement this to do your drawing.
|
||||||||||
|
Called from layout when this view should
assign a size and position to each of its children.
|
||||||||||
|
Measure the view and its content to determine the measured width and the measured height. |
||||||||||
|
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.
|
||||||||||
|
We only want the current page that is being shown to be focusable.
|
||||||||||
|
This is called during layout when the size of this view has changed.
|
||||||||||
|
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
|
Indicates that the pager is currently being dragged by the user.
Indicates that the pager is in an idle, settled state. The current page is fully in view and no animation is in progress.
Indicates that the pager is in the process of settling to a final position.
We only want the current page that is being shown to be focusable.
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. |
We only want the current page that is being shown to be touchable.
views | Touchable views found so far |
---|
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.
child | the child view to add |
---|---|
index | the position at which to add the child |
params | the layout parameters to set on the child |
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.
Check if this view can be scrolled horizontally in a certain direction.
direction | Negative to check scrolling left, positive to check scrolling right. |
---|
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.
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.
event | The key event to be dispatched. |
---|
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
.
event | The event. |
---|
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.
canvas | The Canvas to which the View is rendered. |
---|
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.
event | The key event to execute. |
---|
Fake drag by an offset in pixels. You must have called
beginFakeDrag()
first.
xOffset | Offset in pixels to drag by. |
---|
Returns a new set of layout parameters based on the supplied attributes set.
attrs | the attributes to build the layout parameters from |
---|
ViewGroup.LayoutParams
or one
of its descendants
Retrieve the current adapter supplying pages.
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 the margin between pages.
Returns true if a fake drag is in progress.
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:
ACTION_CANCEL
, and all further
events will be delivered to your onTouchEvent() method and no longer
appear here.
ev | The motion event being dispatched down the hierarchy. |
---|
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.
state |
The frozen state that had previously been returned by
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.
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:
ACTION_CLICK
when
accessibility features are enabled
ev | The motion event. |
---|
Note:
do not invoke this method from
draw(android.graphics.Canvas)
,
onDraw(android.graphics.Canvas)
,
dispatchDraw(android.graphics.Canvas)
or any related method.
Set a PagerAdapter that will supply views for this pager as needed.
adapter | Adapter to use |
---|
Set the currently selected page.
item | Item index to select |
---|---|
smoothScroll | True to smoothly scroll to the new item, false to transition immediately |
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.
item | Item index to select |
---|
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.
limit | How many pages will be kept offscreen in an idle state. |
---|
Set a listener that will be invoked whenever the page changes or is incrementally
scrolled. See
ViewPager.OnPageChangeListener
.
listener | Listener to set |
---|
Set the margin between pages.
marginPixels | Distance between adjacent pages in pixels |
---|
Set a drawable that will be used to fill the margin between pages.
resId | Resource ID of a drawable to display between pages |
---|
Set a drawable that will be used to fill the margin between pages.
d | Drawable to display between pages |
---|
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.
reverseDrawingOrder | true if the supplied PageTransformer requires page views to be drawn from last to first instead of first to last. |
---|---|
transformer | PageTransformer that will modify each page's animation properties |
Tests scrollability within child views of v given a delta of dx.
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 |
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.
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 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.
p | The layout parameters to convert into a suitable set of layout parameters for this ViewGroup. |
---|
ViewGroup.LayoutParams
or one
of its descendants
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)
.
i | The current iteration. |
---|
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)
.
This is called when the view is detached from a window. At this point it no longer has a surface for drawing.
Implement this to do your drawing.
canvas | the canvas on which the background will be drawn |
---|
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.
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 |
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()
).
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
.
|
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.
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. |
We only want the current page that is being shown to be focusable.
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. |
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.
w | Current width of this view. |
---|---|
h | Current height of this view. |
oldw | Old width of this view. |
oldh | Old height of this view. |
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.
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. |
---|