Class ViewPager

All Implemented Interfaces:
Drawable.Callback, ViewManager, ViewParent

public class ViewPager extends ViewGroup
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.
  • Field Details

    • SCROLL_STATE_IDLE

      public static final int SCROLL_STATE_IDLE
      Indicates that the pager is in an idle, settled state. The current page is fully in view and no animation is in progress.
      See Also:
    • SCROLL_STATE_DRAGGING

      public static final int SCROLL_STATE_DRAGGING
      Indicates that the pager is currently being dragged by the user.
      See Also:
    • SCROLL_STATE_SETTLING

      public static final int SCROLL_STATE_SETTLING
      Indicates that the pager is in the process of settling to a final position.
      See Also:
  • Constructor Details

    • ViewPager

      public ViewPager(Context context)
  • Method Details

    • onDetachedFromWindow

      protected void onDetachedFromWindow()
      Description copied from class: View
      This is called when the view is detached from a window. At this point it no longer has a surface for drawing.
      Overrides:
      onDetachedFromWindow in class View
      See Also:
    • setAdapter

      public void setAdapter(@Nullable PagerAdapter adapter)
      Set a PagerAdapter that will supply views for this pager as needed.
      Parameters:
      adapter - Adapter to use
    • getAdapter

      @Nullable public PagerAdapter getAdapter()
      Retrieve the current adapter supplying pages.
      Returns:
      The currently registered PagerAdapter
    • addOnAdapterChangeListener

      public void addOnAdapterChangeListener(@NonNull ViewPager.OnAdapterChangeListener listener)
      Add a listener that will be invoked whenever the adapter for this ViewPager changes.
      Parameters:
      listener - listener to add
    • removeOnAdapterChangeListener

      public void removeOnAdapterChangeListener(@NonNull ViewPager.OnAdapterChangeListener listener)
      Remove a listener that was previously added via addOnAdapterChangeListener(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 select
      smoothScroll - True to smoothly scroll to the new item, false to transition immediately
    • getCurrentItem

      public int getCurrentItem()
    • addOnPageChangeListener

      public void addOnPageChangeListener(@NonNull 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 - listener to add
    • removeOnPageChangeListener

      public void removeOnPageChangeListener(@NonNull ViewPager.OnPageChangeListener listener)
      Remove a listener that was previously added via addOnPageChangeListener(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 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 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 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 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
      pageLayerType - View layer type that should be used for ViewPager pages. It should be either
      invalid reference
      View#LAYER_TYPE_HARDWARE
      ,
      invalid reference
      View#LAYER_TYPE_SOFTWARE
      , or
      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

      public void setPageMarginDrawable(@Nullable Drawable d)
      Set a drawable that will be used to fill the margin between pages.
      Parameters:
      d - Drawable to display between pages
    • setEdgeEffectColor

      public void setEdgeEffectColor(int color)
      Sets the edge effect color for both left and right edge effects.
      Parameters:
      color - The color for the edge effects.
      See Also:
    • setLeftEdgeEffectColor

      public void setLeftEdgeEffectColor(int color)
      Sets the left edge effect color.
      Parameters:
      color - The color for the left edge effect.
      See Also:
    • setRightEdgeEffectColor

      public void setRightEdgeEffectColor(int color)
      Sets the right edge effect color.
      Parameters:
      color - The color for the right edge effect.
      See Also:
    • getLeftEdgeEffectColor

      public int getLeftEdgeEffectColor()
      Returns the left edge effect color.
      Returns:
      The left edge effect color.
      See Also:
    • getRightEdgeEffectColor

      public int getRightEdgeEffectColor()
      Returns the right edge effect color.
      Returns:
      The right edge effect color.
      See Also:
    • setLeftEdgeEffectBlendMode

      public void setLeftEdgeEffectBlendMode(@Nullable BlendMode blendMode)
      Sets the left edge effect blend mode, the default is EdgeEffect.DEFAULT_BLEND_MODE.
      Parameters:
      blendMode - The blend mode for the left edge effect.
    • setRightEdgeEffectBlendMode

      public void setRightEdgeEffectBlendMode(@Nullable BlendMode blendMode)
      Sets the right edge effect blend mode, the default is EdgeEffect.DEFAULT_BLEND_MODE.
      Parameters:
      blendMode - The blend mode for the right edge effect.
    • getLeftEdgeEffectBlendMode

      @Nullable public BlendMode getLeftEdgeEffectBlendMode()
    • getRightEdgeEffectBlendMode

      @Nullable public BlendMode getRightEdgeEffectBlendMode()
    • verifyDrawable

      protected boolean verifyDrawable(@NonNull Drawable drawable)
      Description copied from class: 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.

      Overrides:
      verifyDrawable in class View
      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: View
      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.

      Overrides:
      drawableStateChanged in class ViewGroup
      See Also:
    • getChildDrawingOrder

      protected int getChildDrawingOrder(int childCount, int i)
      Description copied from class: ViewGroup
      Converts 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:
      getChildDrawingOrder in class ViewGroup
      Parameters:
      i - the drawing order position.
      Returns:
      the container position of a child for this drawing order position.
      See Also:
    • addView

      public void addView(@NonNull View child, int index, @NonNull ViewGroup.LayoutParams params)
      Description copied from class: ViewGroup
      Adds 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.

      Overrides:
      addView in class ViewGroup
      Parameters:
      child - the child view to add
      index - the position at which to add the child or -1 to add last
      params - the layout parameters to set on the child
    • removeView

      public void removeView(@NonNull View view)
      Description copied from class: ViewGroup

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

      Specified by:
      removeView in interface ViewManager
      Overrides:
      removeView in class ViewGroup
    • onAttachedToWindow

      protected void onAttachedToWindow()
      Description copied from class: View
      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 View.onDraw(Canvas), however it may be called any time before the first onDraw -- including before or after View.onMeasure(int, int).
      Overrides:
      onAttachedToWindow in class View
      See Also:
    • onMeasure

      protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
      Description copied from class: View
      Measure the view and its content to determine the measured width and the measured height. This method is invoked by View.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 an IllegalStateException, thrown by View.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:
      onMeasure in class View
      Parameters:
      widthMeasureSpec - width measure specification imposed by the parent MeasureSpec
      heightMeasureSpec - height measure specification imposed by the parent MeasureSpec
    • onSizeChanged

      protected void onSizeChanged(int w, int h, int oldw, int oldh)
      Description copied from class: View
      Called when width or height changed
      Overrides:
      onSizeChanged in class View
      Parameters:
      w - new width
      h - new height
      oldw - previous width
      oldh - previous height
    • onLayout

      protected void onLayout(boolean changed, int l, int t, int r, int b)
      Description copied from class: View
      Called from View.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.

      Specified by:
      onLayout in class ViewGroup
      Parameters:
      changed - This is a new size or position for this view
      l - Left position, relative to parent
      t - Top position, relative to parent
      r - Right position, relative to parent
      b - Bottom position, relative to parent
    • computeScroll

      public void computeScroll()
      Description copied from class: View
      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.
      Overrides:
      computeScroll in class View
    • onPageScrolled

      @CallSuper 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.
    • onInterceptTouchEvent

      public boolean onInterceptTouchEvent(MotionEvent ev)
      Description copied from class: ViewGroup
      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 MotionEvent.ACTION_CANCEL, and all further events will be delivered to your onTouchEvent() method and no longer appear here.
      Overrides:
      onInterceptTouchEvent in class ViewGroup
      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

      public boolean onTouchEvent(@NonNull MotionEvent ev)
      Description copied from class: 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 View.performClick(). This will ensure consistent system behavior.

      Overrides:
      onTouchEvent in class View
      Parameters:
      ev - the touch event
      Returns:
      true if the event was handled by the view, false otherwise
    • draw

      public void draw(@NonNull Canvas canvas)
      Description copied from class: View
      Base method that directly draws this view and its background, foreground, overlay and all children to the given canvas. When implementing a view, override View.onDraw(Canvas) instead of this.

      This is not the entry point for the view system to draw.

      Overrides:
      draw in class View
      Parameters:
      canvas - the canvas to draw content
    • onDraw

      protected void onDraw(@NonNull Canvas canvas)
      Description copied from class: View
      Draw 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.

      Overrides:
      onDraw in class View
      Parameters:
      canvas - the canvas to draw content
    • 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. Call endFakeDrag() to complete the fake drag and fling as necessary.

      During a fake drag the ViewPager will ignore all touch events. If a real drag is already in progress, this method will return false.

      Returns:
      true if the fake drag began successfully, false if it could not be started.
      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 called beginFakeDrag() 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:
      canScrollHorizontally in class View
      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

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

      public boolean dispatchKeyEvent(@NonNull KeyEvent event)
      Description copied from class: View
      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.
      Overrides:
      dispatchKeyEvent in class ViewGroup
      Parameters:
      event - The key event to be dispatched.
      Returns:
      True if the event was handled, false otherwise.
    • executeKeyEvent

      public boolean executeKeyEvent(@NonNull KeyEvent event)
      You can call this function yourself to have the scroll view perform scrolling from a key event, just as if the event had been dispatched to it by the view hierarchy.
      Parameters:
      event - The key event to execute.
      Returns:
      Return true if the event was handled, else false.
    • 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 either View.FOCUS_LEFT or View.FOCUS_RIGHT.
      Returns:
      Whether the scrolling was handled successfully.
    • addFocusables

      public void addFocusables(@NonNull ArrayList<View> views, int direction, int focusableMode)
      We only want the current page that is being shown to be focusable.
      Overrides:
      addFocusables in class ViewGroup
      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

      public void addTouchables(@NonNull ArrayList<View> views)
      We only want the current page that is being shown to be touchable.
      Overrides:
      addTouchables in class ViewGroup
      Parameters:
      views - Touchable views found so far
    • onRequestFocusInDescendants

      protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect)
      We only want the current page that is being shown to be focusable.
      Overrides:
      onRequestFocusInDescendants in class ViewGroup
      Parameters:
      direction - One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
      previouslyFocusedRect - The rectangle (in this View's coordinate system) to give a finer grained hint about where focus is coming from. May be null if there is no hint.
      Returns:
      Whether focus was taken.
    • generateDefaultLayoutParams

      @NonNull protected ViewGroup.LayoutParams generateDefaultLayoutParams()
      Description copied from class: ViewGroup
      Returns a set of default layout parameters. These parameters are requested when the View passed to ViewGroup.addView(View) has no layout parameters already set. If null is returned, an exception is thrown from addView.
      Overrides:
      generateDefaultLayoutParams in class ViewGroup
      Returns:
      a set of default layout parameters
    • generateLayoutParams

      @NonNull protected ViewGroup.LayoutParams generateLayoutParams(@NonNull ViewGroup.LayoutParams p)
      Description copied from class: ViewGroup
      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 ViewGroup.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:
      generateLayoutParams in class ViewGroup
      Parameters:
      p - The layout parameters to convert into a suitable set of layout parameters for this ViewGroup.
      Returns:
      an instance of ViewGroup.LayoutParams or one of its descendants
    • checkLayoutParams

      protected boolean checkLayoutParams(ViewGroup.LayoutParams p)
      Description copied from class: ViewGroup
      Check whether given params fit to this view group.

      See also ViewGroup.generateLayoutParams(LayoutParams) See also ViewGroup.generateDefaultLayoutParams()

      Overrides:
      checkLayoutParams in class ViewGroup
      Parameters:
      p - layout params to check
      Returns:
      if params matched to this view group