Class ViewPager
- All Implemented Interfaces:
Drawable.Callback,ViewManager,ViewParent
You supply an implementation of a
PagerAdapter to generate the pages that the view shows.
Views which are annotated with the ViewPager.DecorView annotation are treated as
part of the view pagers 'decor'.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic @interfaceAnnotation which allows marking of views to be decoration views when added to a view pager.static classLayout parameters that should be supplied for views added to a ViewPager.static interfaceCallback interface for responding to adapter changes.static interfaceCallback interface for responding to changing state of the selected page.static interfaceA PageTransformer is invoked whenever a visible/attached page is scrolled.Nested classes/interfaces inherited from class icyllis.modernui.view.ViewGroup
ViewGroup.MarginLayoutParamsNested classes/interfaces inherited from class icyllis.modernui.view.View
View.DragShadow, View.Focusable, View.FocusableMode, View.FocusDirection, View.FocusRealDirection, View.LayoutDir, View.NestedScrollType, View.OnAttachStateChangeListener, View.OnClickListener, View.OnContextClickListener, View.OnCreateContextMenuListener, View.OnDragListener, View.OnFocusChangeListener, View.OnGenericMotionListener, View.OnHoverListener, View.OnKeyListener, View.OnLayoutChangeListener, View.OnLongClickListener, View.OnScrollChangeListener, View.OnTouchListener, View.ResolvedLayoutDir, View.ScrollAxis, View.ScrollBarStyle, View.ScrollIndicators, View.TextAlignment, View.Visibility -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intIndicates that the pager is currently being dragged by the user.static final intIndicates that the pager is in an idle, settled state.static final intIndicates that the pager is in the process of settling to a final position.Fields inherited from class icyllis.modernui.view.ViewGroup
CLIP_TO_PADDING_MASK, FLAG_DISALLOW_INTERCEPT, FOCUS_AFTER_DESCENDANTS, FOCUS_BEFORE_DESCENDANTS, FOCUS_BLOCK_DESCENDANTSFields inherited from class icyllis.modernui.view.View
ALPHA, BOTTOM, EMPTY_STATE_SET, ENABLED_FOCUSED_SELECTED_STATE_SET, ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, ENABLED_FOCUSED_STATE_SET, ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET, ENABLED_SELECTED_STATE_SET, ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET, ENABLED_STATE_SET, ENABLED_WINDOW_FOCUSED_STATE_SET, FOCUS_BACKWARD, FOCUS_DOWN, FOCUS_FORWARD, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_UP, FOCUSABLE, FOCUSABLE_AUTO, FOCUSABLES_ALL, FOCUSABLES_TOUCH_MODE, FOCUSED_SELECTED_STATE_SET, FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, FOCUSED_STATE_SET, FOCUSED_WINDOW_FOCUSED_STATE_SET, GONE, HAPTIC_FEEDBACK_ENABLED, INVISIBLE, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE, LAYOUT_DIRECTION_LTR, LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_UNDEFINED, LEFT, MEASURED_HEIGHT_STATE_SHIFT, MEASURED_SIZE_MASK, MEASURED_STATE_MASK, MEASURED_STATE_TOO_SMALL, NO_ID, NOT_FOCUSABLE, OVER_SCROLL_ALWAYS, OVER_SCROLL_IF_CONTENT_SCROLLS, OVER_SCROLL_NEVER, PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET, PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, PRESSED_ENABLED_FOCUSED_STATE_SET, PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET, PRESSED_ENABLED_SELECTED_STATE_SET, PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET, PRESSED_ENABLED_STATE_SET, PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET, PRESSED_FOCUSED_SELECTED_STATE_SET, PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, PRESSED_FOCUSED_STATE_SET, PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET, PRESSED_SELECTED_STATE_SET, PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET, PRESSED_STATE_SET, PRESSED_WINDOW_FOCUSED_STATE_SET, RIGHT, ROTATION, ROTATION_X, ROTATION_Y, SCALE_X, SCALE_Y, SCROLL_AXIS_HORIZONTAL, SCROLL_AXIS_NONE, SCROLL_AXIS_VERTICAL, SCROLL_INDICATOR_BOTTOM, SCROLL_INDICATOR_END, SCROLL_INDICATOR_LEFT, SCROLL_INDICATOR_RIGHT, SCROLL_INDICATOR_START, SCROLL_INDICATOR_TOP, SCROLL_X, SCROLL_Y, SCROLLBARS_INSIDE_INSET, SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_OUTSIDE_INSET, SCROLLBARS_OUTSIDE_OVERLAY, SELECTED_STATE_SET, SELECTED_WINDOW_FOCUSED_STATE_SET, SOUND_EFFECTS_ENABLED, TEXT_ALIGNMENT_CENTER, TEXT_ALIGNMENT_GRAVITY, TEXT_ALIGNMENT_INHERIT, TEXT_ALIGNMENT_TEXT_END, TEXT_ALIGNMENT_TEXT_START, TEXT_ALIGNMENT_VIEW_END, TEXT_ALIGNMENT_VIEW_START, TEXT_DIRECTION_ANY_RTL, TEXT_DIRECTION_FIRST_STRONG, TEXT_DIRECTION_FIRST_STRONG_LTR, TEXT_DIRECTION_FIRST_STRONG_RTL, TEXT_DIRECTION_INHERIT, TEXT_DIRECTION_LOCALE, TEXT_DIRECTION_LTR, TEXT_DIRECTION_RTL, TOP, TRANSLATION_X, TRANSLATION_Y, TRANSLATION_Z, TYPE_NON_TOUCH, TYPE_TOUCH, VIEW_MARKER, VISIBLE, WINDOW_FOCUSED_STATE_SET, X, Y, Z -
Constructor Summary
ConstructorsConstructorDescriptionViewPager(Context context, AttributeSet attrs) ViewPager(Context context, AttributeSet attrs, ResourceId defStyleAttr) ViewPager(Context context, AttributeSet attrs, ResourceId defStyleAttr, ResourceId defStyleRes) -
Method Summary
Modifier and TypeMethodDescriptionvoidaddFocusables(ArrayList<View> views, int direction, int focusableMode) We only want the current page that is being shown to be focusable.voidAdd a listener that will be invoked whenever the adapter for this ViewPager changes.voidAdd a listener that will be invoked whenever the page changes or is incrementally scrolled.voidaddTouchables(ArrayList<View> views) We only want the current page that is being shown to be touchable.voidaddView(View child, int index, ViewGroup.LayoutParams params) Adds a child view with the specified layout parameters.booleanarrowScroll(int direction) Handle scrolling in response to a left or right arrow click.booleanStart a fake drag of the pager.protected booleanTests scrollability within child views of v given a delta of dx.booleancanScrollHorizontally(int direction) Check if this ViewPager can be scrolled horizontally in a certain direction.protected booleanCheck whether given params fit to this view group.voidRemove all listeners that are notified of any changes in scroll state or position.voidCalled by a parent to request that a child update its values for mScrollX and mScrollY if necessary.booleandispatchKeyEvent(KeyEvent event) Dispatch a key event to the next view on the focus path.voidBase method that directly draws this view and its background, foreground, overlay and all children to the given canvas.protected voidThis function is called whenever the state of the view changes in such a way that it impacts the state of drawables being shown.voidEnd a fake drag of the pager.booleanexecuteKeyEvent(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.voidfakeDragBy(float xOffset) Fake drag by an offset in pixels.protected ViewGroup.LayoutParamsReturns a set of default layout parameters.protected ViewGroup.LayoutParamsReturns a safe set of layout parameters based on the supplied layout params.Retrieve the current adapter supplying pages.protected intgetChildDrawingOrder(int childCount, int i) Converts drawing order position to container position.intintReturns the left edge effect color.intReturns the number of pages that will be retained to either side of the current page in the view hierarchy in an idle state.intReturn the margin between pages.intReturns the right edge effect color.booleanbooleanReturns true if a fake drag is in progress.protected voidThis is called when the view is attached to a window.protected voidThis is called when the view is detached from a window.protected voidDraw the content of this view, implement this to do your drawing.booleanImplement this method to intercept all touch screen motion events.protected voidonLayout(boolean changed, int l, int t, int r, int b) Called fromView.layout(int, int, int, int)when this view should assign a size and position to each of its children.protected voidonMeasure(int widthMeasureSpec, int heightMeasureSpec) Measure the view and its content to determine the measured width and the measured height.protected voidonPageScrolled(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.protected booleanonRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) We only want the current page that is being shown to be focusable.voidonRtlPropertiesChanged(int layoutDirection) Called when any RTL property (layout direction or text direction or text alignment) has been changed.protected voidonSizeChanged(int w, int h, int oldw, int oldh) Called when width or height changedbooleanImplement this method to handle touch screen motion events.voidRemove a listener that was previously added viaaddOnAdapterChangeListener(OnAdapterChangeListener).voidRemove a listener that was previously added viaaddOnPageChangeListener(OnPageChangeListener).voidremoveView(View view) Note: do not invoke this method fromView.draw(Canvas),View.onDraw(Canvas),ViewGroup.dispatchDraw(Canvas)or any related method.voidsetAdapter(PagerAdapter adapter) Set a PagerAdapter that will supply views for this pager as needed.voidsetCurrentItem(int item) Set the currently selected page.voidsetCurrentItem(int item, boolean smoothScroll) Set the currently selected page.voidsetDragInGutterEnabled(boolean enabled) Set whether ViewPager should consume drag events if they are within the gutter (left and right edges) of the ViewPager.voidsetEdgeEffectColor(int color) Sets the edge effect color for both left and right edge effects.voidsetLeftEdgeEffectBlendMode(BlendMode blendMode) Sets the left edge effect blend mode, the default isEdgeEffect.DEFAULT_BLEND_MODE.voidsetLeftEdgeEffectColor(int color) Sets the left edge effect color.voidsetOffscreenPageLimit(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.voidsetPageMargin(int marginPixels) Set the margin between pages.voidSet a drawable that will be used to fill the margin between pages.voidsetPageTransformer(boolean reverseDrawingOrder, ViewPager.PageTransformer transformer) Sets aViewPager.PageTransformerthat will be called for each attached page whenever the scroll position is changed.voidsetPageTransformer(boolean reverseDrawingOrder, ViewPager.PageTransformer transformer, int pageLayerType) Sets aViewPager.PageTransformerthat will be called for each attached page whenever the scroll position is changed.voidsetRightEdgeEffectBlendMode(BlendMode blendMode) Sets the right edge effect blend mode, the default isEdgeEffect.DEFAULT_BLEND_MODE.voidsetRightEdgeEffectColor(int color) Sets the right edge effect color.protected booleanverifyDrawable(Drawable drawable) If your view subclass is displaying its own Drawable objects, it should override this function and return true for any Drawable it is displaying.Methods inherited from class icyllis.modernui.view.ViewGroup
addKeyboardNavigationClusters, addStatesFromChildren, addTransientView, addView, addView, addView, addView, addViewInLayout, addViewInLayout, attachViewToParent, bringChildToFront, childDrawableStateChanged, childHasTransientStateChanged, cleanupLayoutState, clearChildFocus, clearDisappearingChildren, clearFocus, detachAllViewsFromParent, detachViewFromParent, detachViewFromParent, detachViewsFromParent, dispatchDraw, dispatchDrawableHotspotChanged, dispatchFinishTemporaryDetach, dispatchGenericPointerEvent, dispatchHoverEvent, dispatchKeyShortcutEvent, dispatchSetActivated, dispatchSetPressed, dispatchSetSelected, dispatchStartTemporaryDetach, dispatchTouchEvent, dispatchVisibilityChanged, dispatchWindowFocusChanged, dispatchWindowVisibilityChanged, drawChild, endViewTransition, findFocus, focusableViewAvailable, focusSearch, getChildAt, getChildCount, getChildDrawingOrder, getChildMeasureSpec, getChildVisibleRect, getChildVisibleRect, getClipChildren, getClipToPadding, getDescendantFocusability, getFocusedChild, getLayoutTransition, getNestedScrollAxes, getTouchscreenBlocksFocus, getTransientView, getTransientViewCount, getTransientViewIndex, hasBooleanFlag, hasFocus, hasTransientState, indexOfChild, internalSetPadding, invalidateChild, invalidateChildInParent, isChildrenDrawingOrderEnabled, isLayoutSuppressed, isTransitionGroup, jumpDrawablesToCurrentState, layout, measureChild, measureChildren, measureChildWithMargins, offsetChildrenTopAndBottom, offsetDescendantRectToMyCoords, offsetRectIntoDescendantCoords, onChildVisibilityChanged, onCreateDrawableState, onInterceptHoverEvent, onNestedFling, onNestedPreFling, onNestedPreScroll, onNestedScroll, onNestedScrollAccepted, onResolvePointerIcon, onSetLayoutParams, onStartNestedScroll, onStopNestedScroll, onViewAdded, onViewRemoved, removeAllViews, removeAllViewsInLayout, removeDetachedView, removeTransientView, removeViewAt, removeViewInLayout, removeViews, removeViewsInLayout, requestChildFocus, requestChildRectangleOnScreen, requestDisallowInterceptTouchEvent, requestFocus, requestTransitionStart, resetResolvedDrawables, resolveDrawables, resolveLayoutDirection, resolveLayoutParams, resolvePadding, resolveRtlPropertiesIfNeeded, resolveTextAlignment, resolveTextDirection, restoreDefaultFocus, setAddStatesFromChildren, setBooleanFlag, setChildrenDrawingOrderEnabled, setClipChildren, setClipToPadding, setDescendantFocusability, setLayoutTransition, setShadowAlpha, setTouchscreenBlocksFocus, setTransitionGroup, shouldDelayChildPressedState, showContextMenuForChild, startActionModeForChild, startViewTransition, suppressLayout, transformPointToViewLocal, updateViewLayoutMethods inherited from class icyllis.modernui.view.View
addFocusables, addOnAttachStateChangeListener, addOnLayoutChangeListener, awakenScrollBars, awakenScrollBars, callOnClick, cancelLongPress, cancelPendingInputEvents, canReceivePointerEvents, canResolveLayoutDirection, canResolveTextAlignment, canResolveTextDirection, canScrollVertically, combineMeasuredStates, computeHorizontalScrollExtent, computeHorizontalScrollOffset, computeHorizontalScrollRange, computeVerticalScrollExtent, computeVerticalScrollOffset, computeVerticalScrollRange, createContextMenu, dispatchGenericMotionEvent, dispatchNestedFling, dispatchNestedPreFling, dispatchNestedPreScroll, dispatchNestedScroll, dispatchPointerEvent, dp, drawableHotspotChanged, findViewById, findViewByPredicate, findViewByPredicateInsideOut, findViewWithTag, focusSearch, forceHasOverlappingRendering, forceLayout, generateViewId, getAlpha, getAnimationMatrix, getBackground, getBaseline, getBottom, getBoundsOnScreen, getBoundsOnScreen, getClipBounds, getClipBounds, getContentDescription, getContext, getContextMenuInfo, getDefaultSize, getDrawableState, getDrawingRect, getElevation, getFadingEdge, getFadingEdgeLength, getFocusable, getFocusables, getFocusedRect, getForeground, getForegroundGravity, getGlobalVisibleRect, getGlobalVisibleRect, getHandler, getHasOverlappingRendering, getHeight, getHitRect, getHorizontalScrollbarHeight, getHorizontalScrollbarThumbDrawable, getHorizontalScrollbarTrackDrawable, getId, getInverseMatrix, getKeyDispatcherState, getLayoutDirection, getLayoutParams, getLeft, getLocalVisibleRect, getLocationInWindow, getLocationOnScreen, getMatrix, getMeasuredHeight, getMeasuredHeightAndState, getMeasuredState, getMeasuredWidth, getMeasuredWidthAndState, getMinimumHeight, getMinimumWidth, getNextClusterForwardId, getNextFocusDownId, getNextFocusForwardId, getNextFocusLeftId, getNextFocusRightId, getNextFocusUpId, getOnFocusChangeListener, getOnLongClickListener, getOutlineProvider, getOverScrollMode, getPaddingBottom, getPaddingEnd, getPaddingLeft, getPaddingRight, getPaddingStart, getPaddingTop, getParent, getPivotX, getPivotY, getRawLayoutDirection, getRawTextAlignment, getRawTextDirection, getRevealOnFocusHint, getRight, getRootView, getRotation, getRotationX, getRotationY, getScaleX, getScaleY, getScrollBarDefaultDelayBeforeFade, getScrollBarFadeDuration, getScrollBarSize, getScrollBarStyle, getScrollIndicators, getScrollX, getScrollY, getStateDescription, getStateListAnimator, getSuggestedMinimumHeight, getSuggestedMinimumWidth, getTag, getTag, getTextAlignment, getTextDirection, getTooltipText, getTooltipView, getTop, getTouchables, getTransitionAlpha, getTransitionName, getTranslationX, getTranslationY, getTranslationZ, getVerticalFadingEdgeLength, getVerticalScrollbarThumbDrawable, getVerticalScrollbarTrackDrawable, getVerticalScrollbarWidth, getViewRoot, getViewTreeObserver, getVisibility, getWidth, getWindowAttachCount, getWindowVisibility, getX, getY, getZ, handleScrollBarDragging, hasExplicitFocusable, hasFocusable, hasIdentityMatrix, hasNestedScrollingParent, hasOnClickListeners, hasOnLongClickListeners, hasOverlappingRendering, hasTranslationTransientState, hasWindowFocus, invalidate, invalidate, invalidate, invalidateDrawable, invalidateOutline, isActivated, isAttachedToWindow, isClickable, isContextClickable, isDuplicateParentStateEnabled, isEnabled, isFocusable, isFocusableInTouchMode, isFocused, isFocusedByDefault, isForegroundInsidePadding, isHapticFeedbackEnabled, isHorizontalFadingEdgeEnabled, isHorizontalScrollBarEnabled, isHovered, isInLayout, isInScrollingContainer, isInTouchMode, isKeyboardNavigationCluster, isLaidOut, isLayoutDirectionInherited, isLayoutDirectionResolved, isLayoutRequested, isLayoutRtl, isLongClickable, isNestedScrollingEnabled, isPaddingRelative, isPivotSet, isPressed, isRootNamespace, isScrollbarFadingEnabled, isSelected, isShowingLayoutBounds, isShown, isSoundEffectsEnabled, isTemporarilyDetached, isTextAlignmentInherited, isTextAlignmentResolved, isTextDirectionInherited, isTextDirectionResolved, isVerticalFadingEdgeEnabled, isVerticalScrollBarEnabled, isVerticalScrollBarHidden, keyboardNavigationClusterSearch, mapRectFromViewToScreenCoords, measure, mergeDrawableStates, offsetLeftAndRight, offsetTopAndBottom, onCancelPendingInputEvents, onCreateContextMenu, onDragEvent, onDrawForeground, onDrawScrollBars, onFinishTemporaryDetach, onFocusChanged, onGenericMotionEvent, onHoverChanged, onHoverEvent, onKeyDown, onKeyShortcut, onKeyUp, onOverScrolled, onResolveDrawables, onScrollChanged, onStartTemporaryDetach, onVisibilityAggregated, onVisibilityChanged, onWindowFocusChanged, onWindowVisibilityChanged, overScrollBy, performButtonActionOnTouchDown, performClick, performContextClick, performContextClick, performHapticFeedback, performHapticFeedback, performLongClick, performLongClick, playSoundEffect, pointInView, post, postDelayed, postInvalidate, postInvalidateDelayed, postInvalidateOnAnimation, postOnAnimation, postOnAnimationDelayed, refreshDrawableState, removeCallbacks, removeOnAttachStateChangeListener, removeOnLayoutChangeListener, requestFocus, requestFocus, requestLayout, requestRectangleOnScreen, requestRectangleOnScreen, requireViewById, resetPivot, resolveSize, resolveSizeAndState, scheduleDrawable, scrollBy, scrollTo, setActivated, setAlpha, setAnimationMatrix, setBackground, setBottom, setClickable, setClipBounds, setContentDescription, setContextClickable, setDuplicateParentStateEnabled, setElevation, setEnabled, setFocusable, setFocusable, setFocusableInTouchMode, setFocusedByDefault, setFocusedInCluster, setForeground, setForegroundGravity, setFrame, setHapticFeedbackEnabled, setHasTransientState, setHasTranslationTransientState, setHorizontalFadingEdgeEnabled, setHorizontalScrollBarEnabled, setHorizontalScrollbarThumbDrawable, setHorizontalScrollbarTrackDrawable, setHovered, setId, setIsRootNamespace, setKeyboardNavigationCluster, setLayoutDirection, setLayoutParams, setLeft, setLongClickable, setMeasuredDimension, setMinimumHeight, setMinimumWidth, setNestedScrollingEnabled, setNextClusterForwardId, setNextFocusDownId, setNextFocusForwardId, setNextFocusLeftId, setNextFocusRightId, setNextFocusUpId, setOnClickListener, setOnContextClickListener, setOnCreateContextMenuListener, setOnDragListener, setOnFocusChangeListener, setOnGenericMotionListener, setOnHoverListener, setOnKeyListener, setOnLongClickListener, setOnScrollChangeListener, setOnTouchListener, setOutlineProvider, setOverScrollMode, setPadding, setPaddingRelative, setPivotX, setPivotY, setPressed, setRevealOnFocusHint, setRight, setRotation, setRotationX, setRotationY, setScaleX, setScaleY, setScrollBarDefaultDelayBeforeFade, setScrollBarFadeDuration, setScrollbarFadingEnabled, setScrollBarSize, setScrollBarStyle, setScrollIndicators, setScrollIndicators, setScrollX, setScrollY, setSelected, setSoundEffectsEnabled, setStateDescription, setStateListAnimator, setTag, setTag, setTextAlignment, setTextDirection, setTooltipText, setTop, setTransitionAlpha, setTransitionName, setTransitionVisibility, setTranslationX, setTranslationY, setTranslationZ, setVerticalFadingEdgeEnabled, setVerticalScrollBarEnabled, setVerticalScrollbarThumbDrawable, setVerticalScrollbarTrackDrawable, setVisibility, setWillNotDraw, setX, setY, setZ, showContextMenu, showContextMenu, sp, startActionMode, startActionMode, startDragAndDrop, startNestedScroll, stopNestedScroll, toGlobalMotionEvent, toLocalMotionEvent, toString, transformFromViewToWindowSpace, transformMatrixToGlobal, transformMatrixToLocal, unscheduleDrawable, unscheduleDrawable, willNotDrawMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface icyllis.modernui.view.ViewParent
canResolveLayoutDirection, canResolveTextAlignment, canResolveTextDirection, createContextMenu, getLayoutDirection, getParent, getTextAlignment, getTextDirection, isLayoutDirectionResolved, isLayoutRequested, isTextAlignmentResolved, isTextDirectionResolved, keyboardNavigationClusterSearch, requestLayout
-
Field Details
-
SCROLL_STATE_IDLE
public static final int SCROLL_STATE_IDLEIndicates that the pager is in an idle, settled state. The current page is fully in view and no animation is in progress.- See Also:
-
SCROLL_STATE_DRAGGING
public static final int SCROLL_STATE_DRAGGINGIndicates that the pager is currently being dragged by the user.- See Also:
-
SCROLL_STATE_SETTLING
public static final int SCROLL_STATE_SETTLINGIndicates that the pager is in the process of settling to a final position.- See Also:
-
-
Constructor Details
-
ViewPager
-
ViewPager
-
ViewPager
public ViewPager(Context context, @Nullable AttributeSet attrs, @Nullable @AttrRes ResourceId defStyleAttr) -
ViewPager
public ViewPager(Context context, @Nullable AttributeSet attrs, @Nullable @AttrRes ResourceId defStyleAttr, @Nullable @StyleRes ResourceId defStyleRes)
-
-
Method Details
-
onDetachedFromWindow
protected void onDetachedFromWindow()Description copied from class:ViewThis is called when the view is detached from a window. At this point it no longer has a surface for drawing.- Overrides:
onDetachedFromWindowin classView- See Also:
-
setAdapter
Set a PagerAdapter that will supply views for this pager as needed.- Parameters:
adapter- Adapter to use
-
getAdapter
Retrieve the current adapter supplying pages.- Returns:
- The currently registered PagerAdapter
-
addOnAdapterChangeListener
Add a listener that will be invoked whenever the adapter for this ViewPager changes.- Parameters:
listener- listener to add
-
removeOnAdapterChangeListener
Remove a listener that was previously added viaaddOnAdapterChangeListener(OnAdapterChangeListener).- Parameters:
listener- listener to remove
-
setCurrentItem
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
-
setCurrentItem
public void setCurrentItem(int item, boolean smoothScroll) Set the currently selected page.- Parameters:
item- Item index to selectsmoothScroll- True to smoothly scroll to the new item, false to transition immediately
-
getCurrentItem
public int getCurrentItem() -
addOnPageChangeListener
Add a listener that will be invoked whenever the page changes or is incrementally scrolled. SeeViewPager.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- listener to add
-
removeOnPageChangeListener
Remove a listener that was previously added viaaddOnPageChangeListener(OnPageChangeListener).- Parameters:
listener- listener to remove
-
clearOnPageChangeListeners
public void clearOnPageChangeListeners()Remove all listeners that are notified of any changes in scroll state or position. -
setPageTransformer
public void setPageTransformer(boolean reverseDrawingOrder, @Nullable ViewPager.PageTransformer transformer) Sets aViewPager.PageTransformerthat will be called for each attached page whenever the scroll position is changed. This allows the application to apply custom property transformations to each page, overriding the default sliding behavior.- Parameters:
reverseDrawingOrder- 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
-
setPageTransformer
public void setPageTransformer(boolean reverseDrawingOrder, @Nullable ViewPager.PageTransformer transformer, int pageLayerType) Sets aViewPager.PageTransformerthat will be called for each attached page whenever the scroll position is changed. This allows the application to apply custom property transformations to each page, overriding the default sliding behavior.- Parameters:
reverseDrawingOrder- 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 propertiespageLayerType- View layer type that should be used for ViewPager pages. It should be either, orinvalid reference
View#LAYER_TYPE_HARDWARE.invalid reference
View#LAYER_TYPE_NONE
-
getOffscreenPageLimit
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
- See Also:
-
setOffscreenPageLimit
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.
-
setPageMargin
public void setPageMargin(int marginPixels) Set the margin between pages.- Parameters:
marginPixels- Distance between adjacent pages in pixels- See Also:
-
getPageMargin
public int getPageMargin()Return the margin between pages.- Returns:
- The size of the margin in pixels
-
setPageMarginDrawable
Set a drawable that will be used to fill the margin between pages.- Parameters:
d- Drawable to display between pages
-
setEdgeEffectColor
Sets the edge effect color for both left and right edge effects.- Parameters:
color- The color for the edge effects.- See Also:
-
setLeftEdgeEffectColor
Sets the left edge effect color.- Parameters:
color- The color for the left edge effect.- See Also:
-
setRightEdgeEffectColor
Sets the right edge effect color.- Parameters:
color- The color for the right edge effect.- See Also:
-
getLeftEdgeEffectColor
Returns the left edge effect color.- Returns:
- The left edge effect color.
- See Also:
-
getRightEdgeEffectColor
Returns the right edge effect color.- Returns:
- The right edge effect color.
- See Also:
-
setLeftEdgeEffectBlendMode
Sets the left edge effect blend mode, the default isEdgeEffect.DEFAULT_BLEND_MODE.- Parameters:
blendMode- The blend mode for the left edge effect.
-
setRightEdgeEffectBlendMode
Sets the right edge effect blend mode, the default isEdgeEffect.DEFAULT_BLEND_MODE.- Parameters:
blendMode- The blend mode for the right edge effect.
-
getLeftEdgeEffectBlendMode
-
getRightEdgeEffectBlendMode
-
verifyDrawable
Description copied from class:ViewIf 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.
- Overrides:
verifyDrawablein classView- Parameters:
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 If true then the Drawable is being displayed in the view; else false and it is not allowed to animate.
- See Also:
-
drawableStateChanged
protected void drawableStateChanged()Description copied from class:ViewThis 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.
- Overrides:
drawableStateChangedin classViewGroup- See Also:
-
getChildDrawingOrder
protected int getChildDrawingOrder(int childCount, int i) Description copied from class:ViewGroupConverts drawing order position to container position. Override this if you want to change the drawing order of children. By default, it returns drawingPosition.NOTE: In order for this method to be called, you must enable child ordering first by calling
ViewGroup.setChildrenDrawingOrderEnabled(boolean).- Overrides:
getChildDrawingOrderin classViewGroup- Parameters:
i- the drawing order position.- Returns:
- the container position of a child for this drawing order position.
- See Also:
-
addView
Description copied from class:ViewGroupAdds a child view with the specified layout parameters.Note: do not invoke this method from
View.draw(Canvas),View.onDraw(Canvas),ViewGroup.dispatchDraw(Canvas)or any related method. -
removeView
Description copied from class:ViewGroupNote: do not invoke this method from
View.draw(Canvas),View.onDraw(Canvas),ViewGroup.dispatchDraw(Canvas)or any related method.- Specified by:
removeViewin interfaceViewManager- Overrides:
removeViewin classViewGroup
-
onAttachedToWindow
protected void onAttachedToWindow()Description copied from class:ViewThis 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 beforeView.onDraw(Canvas), however it may be called any time before the first onDraw -- including before or afterView.onMeasure(int, int).- Overrides:
onAttachedToWindowin classView- See Also:
-
onMeasure
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) Description copied from class:ViewMeasure the view and its content to determine the measured width and the measured height. This method is invoked byView.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
View.setMeasuredDimension(int, int)to store the measured width and height of this view. Failure to do so will trigger anIllegalStateException, thrown byView.measure(int, int). Calling super.onMeasure() 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 the base one to provide better measurements of their content.
- Overrides:
onMeasurein classView- Parameters:
widthMeasureSpec- width measure specification imposed by the parentMeasureSpecheightMeasureSpec- height measure specification imposed by the parentMeasureSpec
-
onSizeChanged
protected void onSizeChanged(int w, int h, int oldw, int oldh) Description copied from class:ViewCalled when width or height changed- Overrides:
onSizeChangedin classView- Parameters:
w- new widthh- new heightoldw- previous widtholdh- previous height
-
onLayout
protected void onLayout(boolean changed, int l, int t, int r, int b) Description copied from class:ViewCalled fromView.layout(int, int, int, int)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.
-
computeScroll
public void computeScroll()Description copied from class:ViewCalled 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.- Overrides:
computeScrollin classView
-
onPageScrolled
@CallSuper @MustBeInvokedByOverriders 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.
-
isDragInGutterEnabled
public boolean isDragInGutterEnabled()- Returns:
- Whether dragging in the gutter (left and right edges) of the ViewPager is enabled.
-
setDragInGutterEnabled
public void setDragInGutterEnabled(boolean enabled) Set whether ViewPager should consume drag events if they are within the gutter (left and right edges) of the ViewPager. The default valuefalse.- Parameters:
enabled- true if ViewPager should allow drag in gutter, false otherwise
-
onInterceptTouchEvent
Description copied from class:ViewGroupImplement 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:- You will receive the down event here.
- 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.
- 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().
- 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
MotionEvent.ACTION_CANCEL, and all further events will be delivered to your onTouchEvent() method and no longer appear here.
- Overrides:
onInterceptTouchEventin classViewGroup- 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.
-
onTouchEvent
Description copied from class:ViewImplement 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
View.performClick(). This will ensure consistent system behavior.- Overrides:
onTouchEventin classView- Parameters:
ev- the touch event- Returns:
trueif the event was handled by the view,falseotherwise
-
draw
Description copied from class:ViewBase method that directly draws this view and its background, foreground, overlay and all children to the given canvas. When implementing a view, overrideView.onDraw(Canvas)instead of this.This is not the entry point for the view system to draw.
-
onDraw
Description copied from class:ViewDraw the content of this view, implement this to do your drawing.Note that (0, 0) will be the top left of the bounds, and (width, height) will be the bottom right of the bounds.
-
beginFakeDrag
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. CallendFakeDrag()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.
- See Also:
-
endFakeDrag
public void endFakeDrag()End a fake drag of the pager.- See Also:
-
fakeDragBy
public void fakeDragBy(float xOffset) Fake drag by an offset in pixels. You must have calledbeginFakeDrag()first.- Parameters:
xOffset- Offset in pixels to drag by.- See Also:
-
isFakeDragging
public boolean isFakeDragging()Returns true if a fake drag is in progress.- Returns:
- true if currently in a fake drag, false otherwise.
- See Also:
-
canScrollHorizontally
public boolean canScrollHorizontally(int direction) Check if this ViewPager can be scrolled horizontally in a certain direction.- Overrides:
canScrollHorizontallyin classView- Parameters:
direction- Negative to check scrolling left, positive to check scrolling right.- Returns:
- Whether this ViewPager can be scrolled in the specified direction. It will always return false if the specified direction is 0.
-
canScroll
Tests scrollability within child views of v given a delta of dx.- Parameters:
v- View to test for horizontal scrollabilitycheckV- Whether the view v passed should itself be checked for scrollability (true), or just its children (false).dx- Delta scrolled in pixelsx- X coordinate of the active touch pointy- Y coordinate of the active touch point- Returns:
- true if child views of v can be scrolled by delta of dx.
-
dispatchKeyEvent
Description copied from class:ViewDispatch 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.- Overrides:
dispatchKeyEventin classViewGroup- Parameters:
event- The key event to be dispatched.- Returns:
- True if the event was handled, false otherwise.
-
executeKeyEvent
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.
-
arrowScroll
public boolean arrowScroll(int direction) Handle scrolling in response to a left or right arrow click.- Parameters:
direction- The direction corresponding to the arrow key that was pressed. It should be eitherView.FOCUS_LEFTorView.FOCUS_RIGHT.- Returns:
- Whether the scrolling was handled successfully.
-
onRtlPropertiesChanged
public void onRtlPropertiesChanged(int layoutDirection) Description copied from class:ViewCalled when any RTL property (layout direction or text direction or text alignment) has been changed.Subclasses need to override this method to take care of cached information that depends on the resolved layout direction, or to inform child views that inherit their layout direction.
The default implementation does nothing.
- Overrides:
onRtlPropertiesChangedin classView- Parameters:
layoutDirection- the direction of the layout- See Also:
-
addFocusables
We only want the current page that is being shown to be focusable.- Overrides:
addFocusablesin classViewGroup- 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.
-
addTouchables
We only want the current page that is being shown to be touchable.- Overrides:
addTouchablesin classViewGroup- Parameters:
views- Touchable views found so far
-
onRequestFocusInDescendants
We only want the current page that is being shown to be focusable.- Overrides:
onRequestFocusInDescendantsin classViewGroup- Parameters:
direction- One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHTpreviouslyFocusedRect- 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.
-
generateDefaultLayoutParams
Description copied from class:ViewGroupReturns a set of default layout parameters. These parameters are requested when the View passed toViewGroup.addView(View)has no layout parameters already set. If null is returned, an exception is thrown from addView.- Overrides:
generateDefaultLayoutParamsin classViewGroup- Returns:
- a set of default layout parameters
-
generateLayoutParams
Description copied from class:ViewGroupReturns 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 ofViewGroup.checkLayoutParams(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.- Overrides:
generateLayoutParamsin classViewGroup- Parameters:
p- The layout parameters to convert into a suitable set of layout parameters for this ViewGroup.- Returns:
- an instance of
ViewGroup.LayoutParamsor one of its descendants
-
checkLayoutParams
Description copied from class:ViewGroupCheck whether given params fit to this view group.See also
ViewGroup.generateLayoutParams(LayoutParams)See alsoViewGroup.generateDefaultLayoutParams()- Overrides:
checkLayoutParamsin classViewGroup- Parameters:
p- layout params to check- Returns:
- if params matched to this view group
-