Class ScrollView

All Implemented Interfaces:
Drawable.Callback, ViewManager, ViewParent

public class ScrollView extends FrameLayout
A view group that allows the view hierarchy placed within it to be scrolled. Scroll view may have only one direct child placed within it. To add multiple views within the scroll view, make the direct child you add a view group, for example LinearLayout, and place additional views within that LinearLayout.

Never add a

invalid reference
RecyclerView
or ListView to a scroll view. Doing so results in poor user interface performance and a poor user experience.

  • Constructor Details

    • ScrollView

      public ScrollView(Context context)
  • Method Details

    • shouldDelayChildPressedState

      public boolean shouldDelayChildPressedState()
      Description copied from class: ViewGroup
      Return true if the pressed state should be delayed for children or descendants of this ViewGroup. Generally, this should be done for containers that can scroll, such as a List. This prevents the pressed state from appearing when the user is actually trying to scroll the content.

      The default implementation returns true for compatibility reasons. Subclasses that do not scroll should generally override this method and return false.

      Overrides:
      shouldDelayChildPressedState in class ViewGroup
    • setEdgeEffectColor

      public void setEdgeEffectColor(@ColorInt int color)
      Sets the edge effect color for both top and bottom edge effects.
      Parameters:
      color - The color for the edge effects.
      See Also:
    • setBottomEdgeEffectColor

      public void setBottomEdgeEffectColor(@ColorInt int color)
      Sets the bottom edge effect color.
      Parameters:
      color - The color for the bottom edge effect.
      See Also:
    • setTopEdgeEffectColor

      public void setTopEdgeEffectColor(@ColorInt int color)
      Sets the top edge effect color.
      Parameters:
      color - The color for the top edge effect.
      See Also:
    • getTopEdgeEffectColor

      @ColorInt public int getTopEdgeEffectColor()
      Returns the top edge effect color.
      Returns:
      The top edge effect color.
      See Also:
    • getBottomEdgeEffectColor

      @ColorInt public int getBottomEdgeEffectColor()
      Returns the bottom edge effect color.
      Returns:
      The bottom edge effect color.
      See Also:
    • setTopEdgeEffectBlendMode

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

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

      @Nullable public BlendMode getTopEdgeEffectBlendMode()
    • getBottomEdgeEffectBlendMode

      @Nullable public BlendMode getBottomEdgeEffectBlendMode()
    • addView

      public void addView(@NonNull View child)
      Description copied from class: ViewGroup

      Adds a child view. If no layout parameters are already set on the child, the default parameters for this ViewGroup are set on the child.

      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
      See Also:
    • addView

      public void addView(@NonNull View child, int index)
      Description copied from class: ViewGroup
      Adds a child view. If no layout parameters are already set on the child, the default parameters for this ViewGroup are set on the child.

      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
      See Also:
    • addView

      public void addView(@NonNull View child, @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.

      Specified by:
      addView in interface ViewManager
      Overrides:
      addView in class ViewGroup
      Parameters:
      child - the child view to add
      params - the layout parameters to set on the child
    • 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
    • isFillViewport

      public boolean isFillViewport()
      Indicates whether this ScrollView's content is stretched to fill the viewport.
      Returns:
      True if the content fills the viewport, false otherwise.
    • setFillViewport

      public void setFillViewport(boolean fillViewport)
      Indicates this ScrollView whether it should stretch its content height to fill the viewport or not.
      Parameters:
      fillViewport - True to stretch the content's height to the viewport's boundaries, false otherwise.
    • isSmoothScrollingEnabled

      public boolean isSmoothScrollingEnabled()
      Returns:
      Whether arrow scrolling will animate its transition.
    • setSmoothScrollingEnabled

      public void setSmoothScrollingEnabled(boolean smoothScrollingEnabled)
      Set whether arrow scrolling will animate its transition.
      Parameters:
      smoothScrollingEnabled - whether arrow scrolling will animate its transition
    • 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 FrameLayout
      Parameters:
      widthMeasureSpec - width measure specification imposed by the parent MeasureSpec
      heightMeasureSpec - height measure specification imposed by the parent MeasureSpec
    • 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.
    • requestDisallowInterceptTouchEvent

      public void requestDisallowInterceptTouchEvent(boolean disallowIntercept)
      Description copied from interface: ViewParent
      Called when a child does not want this parent and its ancestors to intercept touch events with ViewGroup.onInterceptTouchEvent(MotionEvent).

      This parent should pass this call onto its parents. This parent must obey this request for the duration of the touch (that is, only clear the flag after this parent has received an up or a cancel.

      Specified by:
      requestDisallowInterceptTouchEvent in interface ViewParent
      Overrides:
      requestDisallowInterceptTouchEvent in class ViewGroup
      Parameters:
      disallowIntercept - True if the child does not want the parent to intercept touch events.
    • onInterceptTouchEvent

      public boolean onInterceptTouchEvent(@NonNull 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
    • onGenericMotionEvent

      public boolean onGenericMotionEvent(@NonNull MotionEvent event)
      Description copied from class: View
      Implement this method to handle generic motion events.

      Implementations of this method should check if this view ENABLED and CLICKABLE.

      Overrides:
      onGenericMotionEvent in class View
      Parameters:
      event - the generic motion event being processed.
      Returns:
      true if the event was consumed by the view, false otherwise
    • onOverScrolled

      protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY)
      Description copied from class: View
      Called by View.overScrollBy(int, int, int, int, int, int, int, int, boolean) to respond to the results of an over-scroll operation.
      Overrides:
      onOverScrolled in class View
      Parameters:
      scrollX - New X scroll value in pixels
      scrollY - New Y scroll value in pixels
      clampedX - True if scrollX was clamped to an over-scroll boundary
      clampedY - True if scrollY was clamped to an over-scroll boundary
    • pageScroll

      public boolean pageScroll(int direction)

      Handles scrolling in response to a "page up/down" shortcut press. This method will scroll the view by one page up or down and give the focus to the topmost/bottommost component in the new visible area. If no component is a good candidate for focus, this scrollview reclaims the focus.

      Parameters:
      direction - the scroll direction: View.FOCUS_UP to go one page up or View.FOCUS_DOWN to go one page down
      Returns:
      true if the key event is consumed by this method, false otherwise
    • fullScroll

      public boolean fullScroll(int direction)

      Handles scrolling in response to a "home/end" shortcut press. This method will scroll the view to the top or bottom and give the focus to the topmost/bottommost component in the new visible area. If no component is a good candidate for focus, this scrollview reclaims the focus.

      Parameters:
      direction - the scroll direction: View.FOCUS_UP to go the top of the view or View.FOCUS_DOWN to go the bottom
      Returns:
      true if the key event is consumed by this method, false otherwise
    • arrowScroll

      public boolean arrowScroll(int direction)
      Handle scrolling in response to an up or down arrow click.
      Parameters:
      direction - The direction corresponding to the arrow key that was pressed
      Returns:
      True if we consumed the event, false otherwise
    • smoothScrollBy

      public final boolean smoothScrollBy(int delta)
      Like View.scrollBy(int, int), but scroll smoothly instead of immediately.
      Parameters:
      delta - the number of pixels to scroll by on the Y axis
      Returns:
      if actually scrolled
    • smoothScrollTo

      public final void smoothScrollTo(int y)
      Like scrollTo(int, int), but scroll smoothly instead of immediately.
      Parameters:
      y - the position where to scroll on the Y axis
    • computeVerticalScrollRange

      protected int computeVerticalScrollRange()

      The scroll range of a scroll view is the overall height of all of its children.

      Overrides:
      computeVerticalScrollRange in class View
      Returns:
      the total vertical range represented by the vertical scrollbar

      The default range is the drawing height of this view.

      See Also:
    • computeVerticalScrollOffset

      protected int computeVerticalScrollOffset()
      Description copied from class: View

      Compute the vertical offset of the vertical scrollbar's thumb within the horizontal range. This value is used to compute the position of the thumb within the scrollbar's track.

      The range is expressed in arbitrary units that must be the same as the units used by View.computeVerticalScrollRange() and View.computeVerticalScrollExtent().

      The default offset is the scroll offset of this view.

      Overrides:
      computeVerticalScrollOffset in class View
      Returns:
      the vertical offset of the scrollbar's thumb
      See Also:
    • measureChild

      protected void measureChild(@NonNull View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec)
      Description copied from class: ViewGroup
      Ask one of the children of this view to measure itself, taking into account both the MeasureSpec requirements for this view and its padding. The heavy lifting is done in getChildMeasureSpec.
      Overrides:
      measureChild in class ViewGroup
      Parameters:
      child - The child to measure
      parentWidthMeasureSpec - The width requirements for this view
      parentHeightMeasureSpec - The height requirements for this view
    • measureChildWithMargins

      protected void measureChildWithMargins(@NonNull View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed)
      Description copied from class: ViewGroup
      Ask one of the children of this view to measure itself, taking into account both the MeasureSpec requirements for this view and its padding and margins. The child must have MarginLayoutParams The heavy lifting is done in getChildMeasureSpec.
      Overrides:
      measureChildWithMargins in class ViewGroup
      Parameters:
      child - The child to measure
      parentWidthMeasureSpec - The width requirements for this view
      widthUsed - Extra space that has been used up by the parent horizontally (possibly by other children of the parent)
      parentHeightMeasureSpec - The height requirements for this view
      heightUsed - Extra space that has been used up by the parent vertically (possibly by other children of the 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
    • scrollToDescendant

      public void scrollToDescendant(@NonNull View child)
      Scrolls the view to the given child.
      Parameters:
      child - the View to scroll to
    • computeScrollDeltaToGetChildRectOnScreen

      protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect)
      Compute the amount to scroll in the Y direction in order to get a rectangle completely on the screen (or, if taller than the screen, at least the first screen size chunk of it).
      Parameters:
      rect - The rect.
      Returns:
      The scroll delta.
    • requestChildFocus

      public void requestChildFocus(View child, View focused)
      Description copied from interface: ViewParent
      Called when a child of this parent wants focus
      Specified by:
      requestChildFocus in interface ViewParent
      Overrides:
      requestChildFocus in class ViewGroup
      Parameters:
      child - The child of this ViewParent that wants focus. This view will contain the focused view. It is not necessarily the view that actually has focus.
      focused - The view that is a descendant of child that actually has focus
    • onRequestFocusInDescendants

      protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect)
      When looking for focus in children of a scroll view, need to be a little more careful not to give focus to something that is scrolled off-screen.

      This is more expensive than the default ViewGroup implementation, otherwise this behavior might have been made the default.

      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.
    • requestChildRectangleOnScreen

      public boolean requestChildRectangleOnScreen(@NonNull View child, @NonNull Rect rectangle, boolean immediate)
      Description copied from interface: ViewParent
      Called when a child of this group wants a particular rectangle to be positioned onto the screen. ViewGroups overriding this can trust that:
      • child will be a direct child of this group
      • rectangle will be in the child's content coordinates

      ViewGroups overriding this should uphold the contract:

      • nothing will change if the rectangle is already visible
      • the view port will be scrolled only just enough to make the rectangle visible
      Specified by:
      requestChildRectangleOnScreen in interface ViewParent
      Overrides:
      requestChildRectangleOnScreen in class ViewGroup
      Parameters:
      child - The direct child making the request.
      rectangle - The rectangle in the child's coordinates the child wishes to be on the screen.
      immediate - True to forbid animated or delayed scrolling, false otherwise
      Returns:
      Whether the group scrolled to handle the operation
    • requestLayout

      public void requestLayout()
      Description copied from class: View
      Call this when something has changed which has invalidated the layout of this view. This will schedule a layout pass of the view tree. This should not be called while the view hierarchy is currently in a layout pass (View.isInLayout(). If layout is happening, the request may be honored at the end of the current layout pass (and then layout will run again) or after the current frame is drawn and the next layout occurs.

      Subclasses which override this method should call the superclass method to handle possible request-during-layout errors correctly.

      Specified by:
      requestLayout in interface ViewParent
      Overrides:
      requestLayout in class View
    • 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.

      Overrides:
      onLayout in class FrameLayout
      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
    • onSizeChanged

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

      public void fling(int velocityY)
      Fling the scroll view
      Parameters:
      velocityY - The initial velocity in the Y direction. Positive numbers mean that the finger/cursor is moving down the screen, which means we want to scroll towards the top.
    • scrollTo

      public void scrollTo(int x, int y)
      Set the scrolled position of your view. This will cause a call to View.onScrollChanged(int, int, int, int) and the view will be invalidated.

      This version also clamps the scrolling to the bounds of our child.

      Overrides:
      scrollTo in class View
      Parameters:
      x - the x position to scroll to
      y - the y position to scroll to
    • onStartNestedScroll

      public boolean onStartNestedScroll(@NonNull View child, @NonNull View target, int axes, int type)
      Description copied from interface: ViewParent
      React to a descendant view initiating a nestable scroll operation, claiming the nested scroll operation if appropriate.

      This method will be called in response to a descendant view invoking View.startNestedScroll(int, int). Each parent up the view hierarchy will be given an opportunity to respond and claim the nested scrolling operation by returning true.

      This method may be overridden by ViewParent implementations to indicate when the view is willing to support a nested scrolling operation that is about to begin. If it returns true, this ViewParent will become the target view's nested scrolling parent for the duration of the scroll operation in progress. When the nested scroll is finished this ViewParent will receive a call to ViewParent.onStopNestedScroll(View, int).

      Specified by:
      onStartNestedScroll in interface ViewParent
      Overrides:
      onStartNestedScroll in class ViewGroup
      Parameters:
      child - Direct child of this ViewParent containing target
      target - View that initiated the nested scroll
      axes - Flags consisting of View.SCROLL_AXIS_HORIZONTAL, View.SCROLL_AXIS_VERTICAL or both
      type - the type of input which cause this scroll event
      Returns:
      true if this ViewParent accepts the nested scroll operation
    • onNestedScrollAccepted

      public void onNestedScrollAccepted(@NonNull View child, @NonNull View target, int axes, int type)
      Description copied from interface: ViewParent
      React to the successful claiming of a nested scroll operation.

      This method will be called after onStartNestedScroll returns true. It offers an opportunity for the view and its superclasses to perform initial configuration for the nested scroll. Implementations of this method should always call their superclasses' implementation of this method if one is present.

      Specified by:
      onNestedScrollAccepted in interface ViewParent
      Overrides:
      onNestedScrollAccepted in class ViewGroup
      Parameters:
      child - Direct child of this ViewParent containing target
      target - View that initiated the nested scroll
      axes - Flags consisting of View.SCROLL_AXIS_HORIZONTAL, View.SCROLL_AXIS_VERTICAL or both
      type - the type of input which cause this scroll event
      See Also:
    • onNestedScroll

      public void onNestedScroll(@NonNull View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type, @NonNull int[] consumed)
      Description copied from interface: ViewParent
      React to a nested scroll in progress.

      This method will be called when the ViewParent's current nested scrolling child view dispatches a nested scroll event. To receive calls to this method the ViewParent must have previously returned true for a call to ViewParent.onStartNestedScroll(View, View, int, int).

      Both the consumed and unconsumed portions of the scroll distance are reported to the ViewParent. An implementation may choose to use the consumed portion to match or chase scroll position of multiple child elements, for example. The unconsumed portion may be used to allow continuous dragging of multiple scrolling or draggable elements, such as scrolling a list within a vertical drawer where the drawer begins dragging once the edge of inner scrolling content is reached.

      This method is called when a nested scrolling child invokes View.dispatchNestedScroll(int, int, int, int, int[], int, int[])} or one of methods it overloads.

      An implementation must report how many pixels of the x and y scroll distances were consumed by this nested scrolling parent by adding the consumed distances to the consumed parameter. consumed should also be passed up to it's nested scrolling parent so that the parent may also add any scroll distance it consumes. Index 0 corresponds to dx and index 1 corresponds to dy.

      Specified by:
      onNestedScroll in interface ViewParent
      Overrides:
      onNestedScroll in class ViewGroup
      Parameters:
      target - The descendant view controlling the nested scroll
      dxConsumed - Horizontal scroll distance in pixels already consumed by target
      dyConsumed - Vertical scroll distance in pixels already consumed by target
      dxUnconsumed - Horizontal scroll distance in pixels not consumed by target
      dyUnconsumed - Vertical scroll distance in pixels not consumed by target
      type - the type of input which cause this scroll event
      consumed - Output. Upon this method returning, will contain the scroll distances consumed by this nested scrolling parent and the scroll distances consumed by any other parent up the view hierarchy
      See Also:
    • onNestedFling

      public boolean onNestedFling(@NonNull View target, float velocityX, float velocityY, boolean consumed)
      Description copied from interface: ViewParent
      Request a fling from a nested scroll.

      This method signifies that a nested scrolling child has detected suitable conditions for a fling. Generally this means that a touch scroll has ended with a velocity in the direction of scrolling that meets or exceeds the minimum fling velocity along a scrollable axis.

      If a nested scrolling child view would normally fling but it is at the edge of its own content, it can use this method to delegate the fling to its nested scrolling parent instead. The parent may optionally consume the fling or observe a child fling.

      Specified by:
      onNestedFling in interface ViewParent
      Overrides:
      onNestedFling in class ViewGroup
      Parameters:
      target - View that initiated the nested scroll
      velocityX - Horizontal velocity in pixels per second
      velocityY - Vertical velocity in pixels per second
      consumed - true if the child consumed the fling, false otherwise
      Returns:
      true if this parent consumed or otherwise reacted to the fling
    • onDrawForeground

      public void onDrawForeground(@NonNull Canvas canvas)
      Description copied from class: View
      Draw any foreground content for this view.

      Foreground content may consist of scroll bars, a foreground drawable or other view-specific decorations. The foreground is drawn on top of the primary view content.

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