Class View

java.lang.Object
icyllis.modernui.view.View
All Implemented Interfaces:
Drawable.Callback
Direct Known Subclasses:
ImageView, LinearPagerIndicator, ProgressBar, TextView, ViewGroup

@UiThread public class View extends Object implements Drawable.Callback

This class represents the basic building block for user interface components. A View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components (buttons, text fields, etc.). The ViewGroup subclass is the base class for layouts, which are invisible containers that hold other Views (or other ViewGroups) and define their layout properties.

Developer Guides

For information about using this class to develop your application's user interface, read the User Interface developer guide.

Using Views

All of the views in a window are arranged in a single tree. You can add views from code. There are many specialized subclasses of views that act as controls or are capable of displaying text, images, or other content.

Once you have created a tree of views, there are typically a few types of common operations you may wish to perform:

  • Set properties: for example setting the text of a TextView. The available properties and the methods that set them will vary among the different subclasses of views.
  • Set focus: The framework will handle moving focus in response to user input. To force focus to a specific view, call requestFocus().
  • Set up listeners: Views allow clients to set listeners that will be notified when something interesting happens to the view. For example, all views will let you set a listener to be notified when the view gains or loses focus. You can register such a listener using setOnFocusChangeListener(OnFocusChangeListener). Other view subclasses offer more specialized listeners. For example, a Button exposes a listener to notify clients when the button is clicked.
  • Set visibility: You can hide or show views using setVisibility(int).

Note: Modern UI view system is responsible for measuring, laying out and drawing views. You should not call methods that perform these actions on views yourself unless you are actually implementing a ViewGroup.

Measure ...

Layout ...

Attaching ...

Hierarchy ...

Drawing Contents ...

Text Input & Drawing ...

Scrolling ...

Event Handling ... Native Events & Derivative Events

Listeners ...

Custom View ...

Since:
2.0
See Also:
  • Field Details

  • Constructor Details

    • View

      public View(Context context)
      Simple constructor to use when creating a view from code.
  • Method Details

    • isShowingLayoutBounds

      public final boolean isShowingLayoutBounds()
      Returns true when the View is attached and the system developer setting to show the layout bounds is enabled or false otherwise.
    • draw

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

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

      Parameters:
      canvas - the canvas to draw content
    • onDraw

      protected void onDraw(@NonNull Canvas canvas)
      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.

      Parameters:
      canvas - the canvas to draw content
    • dispatchDraw

      protected void dispatchDraw(@NonNull Canvas canvas)
      Draw the child views.
      Parameters:
      canvas - the canvas to draw content
    • onDrawForeground

      public void onDrawForeground(@NonNull Canvas canvas)
      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.

      Parameters:
      canvas - the canvas to draw content
    • onDrawScrollBars

      protected final void onDrawScrollBars(@NonNull Canvas canvas)

      Request the drawing of the horizontal and the vertical scrollbar. The scrollbars are painted only if they have been awakened first.

      Parameters:
      canvas - the canvas on which to draw the scrollbars
      See Also:
    • layout

      public void layout(int l, int t, int r, int b)
      Specifies the rectangle area of this view and all its descendants.

      Derived classes should NOT override this method for any reason. Derived classes with children should override onLayout(boolean, int, int, int, int). In that method, they should call layout() on each of their children.

      Parameters:
      l - left position, relative to parent
      t - top position, relative to parent
      r - right position, relative to parent
      b - bottom position, relative to parent
    • onLayout

      protected void onLayout(boolean changed, int left, int top, int right, int bottom)
      Called from 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.

      Parameters:
      changed - This is a new size or position for this view
      left - Left position, relative to parent
      top - Top position, relative to parent
      right - Right position, relative to parent
      bottom - Bottom position, relative to parent
    • setFrame

      protected boolean setFrame(int left, int top, int right, int bottom)
      Assign a size and position to this view.

      Called from layout(int, int, int, int).

      Parameters:
      left - left position, relative to parent
      top - top position, relative to parent
      right - right position, relative to parent
      bottom - bottom position, relative to parent
      Returns:
      whether the area of this view was changed
    • onSizeChanged

      protected void onSizeChanged(int width, int height, int prevWidth, int prevHeight)
      Called when width or height changed
      Parameters:
      width - new width
      height - new height
      prevWidth - previous width
      prevHeight - previous height
    • measure

      public final void measure(int widthMeasureSpec, int heightMeasureSpec)
      This is called to find out how big a view should be. The parent supplies constraint information in the width and height parameters.

      This method is used to post the onMeasure() event, and the actual measurement work is performed in onMeasure(int, int).

      Parameters:
      widthMeasureSpec - width measure specification imposed by the parent
      heightMeasureSpec - height measure specification imposed by the parent
      Throws:
      IllegalStateException - measured dimension is not set in onMeasure(int, int)
      See Also:
    • onMeasure

      protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
      Measure the view and its content to determine the measured width and the measured height. This method is invoked by measure(int, int) and should be overridden by subclasses to provide accurate and efficient measurement of their contents.

      CONTRACT: When overriding this method, you must call setMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger an IllegalStateException, thrown by measure(int, int). Calling 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.

      Parameters:
      widthMeasureSpec - width measure specification imposed by the parent MeasureSpec
      heightMeasureSpec - height measure specification imposed by the parent MeasureSpec
    • setMeasuredDimension

      protected final void setMeasuredDimension(int measuredWidth, int measuredHeight)
      Set the measured dimension, must be called by onMeasure(int, int)
      Parameters:
      measuredWidth - the measured width of this view
      measuredHeight - the measured height of this view
    • getMeasuredWidth

      public final int getMeasuredWidth()
      Like getMeasuredWidthAndState(), but only returns the raw width component (that is the result is masked by MEASURED_SIZE_MASK).
      Returns:
      The raw measured width of this view.
    • getMeasuredWidthAndState

      public final int getMeasuredWidthAndState()
      Return the full width measurement information for this view as computed by the most recent call to measure(int, int). This result is a bit mask as defined by MEASURED_SIZE_MASK and MEASURED_STATE_TOO_SMALL. This should be used during measurement and layout calculations only. Use getWidth() to see how wide a view is after layout.
      Returns:
      The measured width of this view as a bit mask.
    • getMeasuredHeight

      public final int getMeasuredHeight()
      Like getMeasuredHeightAndState(), but only returns the raw height component (that is the result is masked by MEASURED_SIZE_MASK).
      Returns:
      The raw measured height of this view.
    • getMeasuredHeightAndState

      public final int getMeasuredHeightAndState()
      Return the full height measurement information for this view as computed by the most recent call to measure(int, int). This result is a bit mask as defined by MEASURED_SIZE_MASK and MEASURED_STATE_TOO_SMALL. This should be used during measurement and layout calculations only. Use getHeight() to see how high a view is after layout.
      Returns:
      The measured height of this view as a bit mask.
    • getMeasuredState

      public final int getMeasuredState()
      Return only the state bits of getMeasuredWidthAndState() and getMeasuredHeightAndState(), combined into one integer. The width component is in the regular bits MEASURED_STATE_MASK and the height component is at the shifted bits MEASURED_HEIGHT_STATE_SHIFT>>MEASURED_STATE_MASK.
    • getLayoutParams

      public ViewGroup.LayoutParams getLayoutParams()
      Get the LayoutParams associated with this view. All views should have layout parameters. These supply parameters to the parent of this view specifying how it should be arranged. There are many subclasses of ViewGroup.LayoutParams, and these correspond to the different subclasses of ViewGroup that are responsible for arranging their children.

      This method may return null if this View is not attached to a parent ViewGroup or setLayoutParams(ViewGroup.LayoutParams) was not invoked successfully. When a View is attached to a parent ViewGroup, this method must not return null.

      Returns:
      the LayoutParams associated with this view, or null if no parameters have been set yet
    • setLayoutParams

      public void setLayoutParams(@NonNull ViewGroup.LayoutParams params)
      Set the layout parameters associated with this view. These supply parameters to the parent of this view specifying how it should be arranged. There are many subclasses of ViewGroup.LayoutParams, and these correspond to the different subclasses of ViewGroup that are responsible for arranging their children.
      Parameters:
      params - layout parameters for this view
    • resolveLayoutParams

      @Internal public void resolveLayoutParams()
      Resolve the layout parameters depending on the resolved layout direction
    • combineMeasuredStates

      public static int combineMeasuredStates(int curState, int newState)
      Merge two states as returned by getMeasuredState().
      Parameters:
      curState - The current state as returned from a view or the result of combining multiple views.
      newState - The new view state to combine.
      Returns:
      Returns a new integer reflecting the combination of the two states.
    • resolveSize

      public static int resolveSize(int size, int measureSpec)
      Version of resolveSizeAndState(int, int, int) returning only the MEASURED_SIZE_MASK bits of the result.
    • resolveSizeAndState

      public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState)
      Utility to reconcile a desired size and state, with constraints imposed by a MeasureSpec. Will take the desired size, unless a different size is imposed by the constraints. The returned value is a compound integer, with the resolved size in the MEASURED_SIZE_MASK bits and optionally the bit MEASURED_STATE_TOO_SMALL set if the resulting size is smaller than the size the view wants to be.
      Parameters:
      size - How big the view wants to be.
      measureSpec - Constraints imposed by the parent.
      childMeasuredState - Size information bit mask for the view's children.
      Returns:
      Size information bit mask as defined by MEASURED_SIZE_MASK and MEASURED_STATE_TOO_SMALL.
    • getDefaultSize

      public static int getDefaultSize(int size, int measureSpec)
      Utility to return a default size. Uses the supplied size if the MeasureSpec imposed no constraints. Will get larger if allowed by the MeasureSpec.
      Parameters:
      size - Default size for this view
      measureSpec - Constraints imposed by the parent
      Returns:
      The size this view should be.
    • dp

      public final int dp(float value)
      Utility to get the size in pixels that matches the view layout standards.
      Parameters:
      value - density-independent pixel, relative to other views
      Returns:
      converted size in pixels
    • sp

      public final int sp(float value)
      Utility to get the size in pixels that matches the text layout standards.
      Parameters:
      value - scaling-independent pixel, relative to other texts
      Returns:
      converted size in pixels
    • getSuggestedMinimumHeight

      protected int getSuggestedMinimumHeight()
      Returns the suggested minimum height that the view should use. This returns the maximum of the view's minimum height and the background's minimum height (Drawable.getMinimumHeight()).

      When being used in onMeasure(int, int), the caller should still ensure the returned height is within the requirements of the parent.

      Returns:
      The suggested minimum height of the view.
    • getSuggestedMinimumWidth

      protected int getSuggestedMinimumWidth()
      Returns the suggested minimum width that the view should use. This returns the maximum of the view's minimum width and the background's minimum width (Drawable.getMinimumWidth()).

      When being used in onMeasure(int, int), the caller should still ensure the returned width is within the requirements of the parent.

      Returns:
      The suggested minimum width of the view.
    • getMinimumWidth

      public int getMinimumWidth()
      Returns the minimum width of the view.
      Returns:
      the minimum width the view will try to be, in pixels
      See Also:
    • setMinimumWidth

      public void setMinimumWidth(int minWidth)
      Sets the minimum width of the view. It is not guaranteed the view will be able to achieve this minimum width (for example, if its parent layout constrains it with less available width).
      Parameters:
      minWidth - The minimum width the view will try to be, in pixels
      See Also:
    • getMinimumHeight

      public int getMinimumHeight()
      Returns the minimum height of the view.
      Returns:
      the minimum height the view will try to be, in pixels
      See Also:
    • setMinimumHeight

      public void setMinimumHeight(int minHeight)
      Sets the minimum height of the view. It is not guaranteed the view will be able to achieve this minimum height (for example, if its parent layout constrains it with less available height).
      Parameters:
      minHeight - The minimum height the view will try to be, in pixels
      See Also:
    • getParent

      @Nullable public final ViewParent getParent()
      Gets the parent of this view. Note the parent is not necessarily a View.
      Returns:
      the parent of this view
    • setIsRootNamespace

      @Internal public void setIsRootNamespace(boolean isRoot)
      Parameters:
      isRoot - true if the view belongs to the root namespace, false otherwise
    • isRootNamespace

      @Internal public boolean isRootNamespace()
      Returns:
      true if the view belongs to the root namespace, false otherwise
    • getId

      public int getId()
      Returns this view's identifier.
      Returns:
      a positive integer used to identify the view or NO_ID if the view has no ID
      See Also:
    • setId

      public void setId(int id)
      Sets the identifier for this view. The identifier does not have to be unique in this view's hierarchy. The identifier should be a positive integer.

      For manually generated identifiers, the high 8 bits should be ranged from 0x3F to 0x7F, and the next 8 bits should be 0x02. Otherwise, the high 16 bits should be zero, and low 16 bits should be ranged from 1 to 0xFFFF.

      Parameters:
      id - a number used to identify the view
      See Also:
    • generateViewId

      public static int generateViewId()
      Generate a value suitable for use in setId(int). The range is from 0x10000 to 0xFFFFFF.
      Returns:
      a generated ID value
    • getTag

      @Nullable public Object getTag(int key)
      Returns the tag associated with this view and the specified key.
      Parameters:
      key - The key identifying the tag
      Returns:
      the Object stored in this view as a tag, or null if not set
      See Also:
    • setTag

      public void setTag(int key, Object tag)
      Sets a tag associated with this view and a key. A tag can be used to mark a view in its hierarchy and does not have to be unique within the hierarchy. Tags can also be used to store data within a view without resorting to another data structure.
      Parameters:
      key - The key identifying the tag
      tag - An Object to tag the view with
      Throws:
      IllegalArgumentException - If they specified key is not valid
      See Also:
    • getVisibility

      public int getVisibility()
      Returns the visibility status for this view.
      Returns:
      One of VISIBLE, INVISIBLE, or GONE.
    • setVisibility

      public void setVisibility(int visibility)
      Set the visibility state of this view.
      Parameters:
      visibility - One of VISIBLE, INVISIBLE, or GONE.
    • isEnabled

      public boolean isEnabled()
      Returns the enabled status for this view. The interpretation of the enabled state varies by subclass.
      Returns:
      True if this view is enabled, false otherwise.
    • setEnabled

      public void setEnabled(boolean enabled)
      Set the enabled state of this view. The interpretation of the enabled state varies by subclass.
      Parameters:
      enabled - True if this view is enabled, false otherwise.
    • isFocusable

      public final boolean isFocusable()
      Returns whether this View is currently able to take focus.
      Returns:
      True if this view can take focus, or false otherwise.
    • getFocusable

      public int getFocusable()
      Returns the focusable setting for this view.
      Returns:
      One of NOT_FOCUSABLE, FOCUSABLE, or FOCUSABLE_AUTO.
    • setFocusable

      public void setFocusable(boolean focusable)
      Set whether this view can receive the focus.

      Setting this to false will also ensure that this view is not focusable in touch mode.

      Parameters:
      focusable - If true, this view can receive the focus.
      See Also:
    • setFocusable

      public void setFocusable(int focusable)
      Sets whether this view can receive focus.

      Setting this to FOCUSABLE_AUTO tells the framework to determine focusability automatically based on the view's interactivity. This is the default.

      Setting this to NOT_FOCUSABLE will ensure that this view is also not focusable in touch mode.

      Parameters:
      focusable - One of NOT_FOCUSABLE, FOCUSABLE, or FOCUSABLE_AUTO.
      See Also:
    • isFocusableInTouchMode

      public final boolean isFocusableInTouchMode()
      When a view is focusable, it may not want to take focus when in touch mode. For example, a button would like focus when the user is navigating via a D-pad so that the user can click on it, but once the user starts touching the screen, the button shouldn't take focus
      Returns:
      Whether the view is focusable in touch mode.
    • setFocusableInTouchMode

      public void setFocusableInTouchMode(boolean focusableInTouchMode)
      Set whether this view can receive focus while in touch mode.

      Setting this to true will also ensure that this view is focusable.

      Parameters:
      focusableInTouchMode - If true, this view can receive the focus while in touch mode.
      See Also:
    • isClickable

      public boolean isClickable()
      Indicates whether this view reacts to click events or not.
      Returns:
      true if the view is clickable, false otherwise
      See Also:
    • setClickable

      public void setClickable(boolean clickable)
      Enables or disables click events for this view. When a view is clickable it will change its state to "pressed" on every click. Subclasses should set the view clickable to visually react to user's clicks.
      Parameters:
      clickable - true to make the view clickable, false otherwise
      See Also:
    • isLongClickable

      public boolean isLongClickable()
      Indicates whether this view reacts to long click events or not.
      Returns:
      true if the view is long clickable, false otherwise
      See Also:
    • setLongClickable

      public void setLongClickable(boolean longClickable)
      Enables or disables long click events for this view. When a view is long clickable it reacts to the user holding down the button for a longer duration than a tap. This event can either launch the listener or a context menu.
      Parameters:
      longClickable - true to make the view long clickable, false otherwise
      See Also:
    • isContextClickable

      public boolean isContextClickable()
      Indicates whether this view reacts to context clicks or not.
      Returns:
      true if the view is context clickable, false otherwise
      See Also:
    • setContextClickable

      public void setContextClickable(boolean contextClickable)
      Enables or disables context clicking for this view. This event can launch the listener.
      Parameters:
      contextClickable - true to make the view react to a context click, false otherwise
      See Also:
    • setPressed

      public void setPressed(boolean pressed)
      Sets the pressed state for this view.
      Parameters:
      pressed - Pass true to set the View's internal state to "pressed", or false to reverts the View's internal state from a previously set "pressed" state.
      See Also:
    • dispatchSetPressed

      protected void dispatchSetPressed(boolean pressed)
      Dispatch setPressed to all of this View's children.
      Parameters:
      pressed - The new pressed state
      See Also:
    • isPressed

      public boolean isPressed()
      Indicates whether the view is currently in pressed state. Unless setPressed(boolean) is explicitly called, only clickable views can enter the pressed state.
      Returns:
      true if the view is currently pressed, false otherwise
      See Also:
    • setSelected

      public void setSelected(boolean selected)
      Changes the selection state of this view. A view can be selected or not. Note that selection is not the same as focus. Views are typically selected in the context of an AdapterView like ListView or GridView; the selected view is the view that is highlighted.
      Parameters:
      selected - true if the view must be selected, false otherwise
    • dispatchSetSelected

      protected void dispatchSetSelected(boolean selected)
      Dispatch setSelected to all of this View's children.
      Parameters:
      selected - The new selected state
      See Also:
    • isSelected

      public boolean isSelected()
      Indicates the selection state of this view.
      Returns:
      true if the view is selected, false otherwise
    • setActivated

      public void setActivated(boolean activated)
      Changes the activated state of this view. A view can be activated or not. Note that activation is not the same as selection. Selection is a transient property, representing the view (hierarchy) the user is currently interacting with. Activation is a longer-term state that the user can move views in and out of. For example, in a list view with single or multiple selection enabled, the views in the current selection set are activated. (Um, yeah, we are deeply sorry about the terminology here.) The activated state is propagated down to children of the view it is set on.
      Parameters:
      activated - true if the view must be activated, false otherwise
    • dispatchSetActivated

      protected void dispatchSetActivated(boolean activated)
      Dispatch setActivated to all of this View's children.
      Parameters:
      activated - The new activated state
      See Also:
    • isActivated

      public boolean isActivated()
      Indicates the activation state of this view.
      Returns:
      true if the view is activated, false otherwise
    • invalidate

      public final void invalidate()
      Invalidate the whole view. If the view is visible, onDraw(Canvas) will be called at some point in the future.

      This must be called from a UI thread. To call from a non-UI thread, call postInvalidate().

    • invalidateDrawable

      public void invalidateDrawable(@NonNull Drawable drawable)
      Invalidates the specified Drawable.
      Specified by:
      invalidateDrawable in interface Drawable.Callback
      Parameters:
      drawable - the drawable to invalidate
    • scheduleDrawable

      public final void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when)
      Schedules an action on a drawable to occur at a specified time.
      Specified by:
      scheduleDrawable in interface Drawable.Callback
      Parameters:
      who - the recipient of the action
      what - the action to run on the drawable
      when - the time at which the action must occur. Uses the Core.timeMillis() timebase.
    • unscheduleDrawable

      public final void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what)
      Cancels a scheduled action on a drawable.
      Specified by:
      unscheduleDrawable in interface Drawable.Callback
      Parameters:
      who - the recipient of the action
      what - the action to cancel
    • unscheduleDrawable

      public final void unscheduleDrawable(@Nullable Drawable who)
      Unschedule any events associated with the given Drawable. This can be used when selecting a new Drawable into a view, so that the previous one is completely unscheduled.
      Parameters:
      who - The Drawable to unschedule.
      See Also:
    • getFocusables

      @NonNull public final ArrayList<View> getFocusables(int direction)
      Find and return all focusable views that are descendants of this view, possibly including this view if it is focusable itself.
      Parameters:
      direction - The direction of the focus
      Returns:
      A list of focusable views
    • addFocusables

      public final void addFocusables(ArrayList<View> views, int direction)
      Add any focusable views that are descendants of this view (possibly including this view if it is focusable itself) to views. If we are in touch mode, only add views that are also focusable in touch mode.
      Parameters:
      views - Focusable views found so far
      direction - The direction of the focus
    • addFocusables

      public void addFocusables(@NonNull ArrayList<View> views, int direction, int focusableMode)
      Adds any focusable views that are descendants of this view (possibly including this view if it is focusable itself) to views. This method adds all focusable views regardless if we are in touch mode or only views focusable in touch mode if we are in touch mode or only views that can take accessibility focus if accessibility is enabled depending on the focusable mode parameter.
      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.
    • addKeyboardNavigationClusters

      public void addKeyboardNavigationClusters(@NonNull Collection<View> views, int direction)
      Adds any keyboard navigation cluster roots that are descendants of this view (possibly including this view if it is a cluster root itself) to views.
      Parameters:
      views - Keyboard navigation cluster roots found so far
      direction - Direction to look
    • getTouchables

      @NonNull public final ArrayList<View> getTouchables()
      Find and return all touchable views that are descendants of this view, possibly including this view if it is touchable itself.
      Returns:
      A list of touchable views
    • addTouchables

      public void addTouchables(@NonNull ArrayList<View> views)
      Add any touchable views that are descendants of this view (possibly including this view if it is touchable itself) to views.
      Parameters:
      views - Touchable views found so far
    • requestFocus

      public final boolean requestFocus()
      Call this to try to give focus to a specific view or to one of its descendants.

      A view will not actually take focus if it is not focusable (isFocusable() returns false), or if it can't be focused due to other conditions (not focusable in touch mode (isFocusableInTouchMode()) while the device is in touch mode, not visible, not enabled, or has no size).

      See also focusSearch(int), which is what you call to say that you have focus, and you want your parent to look for the next one.

      This is equivalent to calling requestFocus(int, Rect) with arguments FOCUS_DOWN and null.

      Returns:
      Whether this view or one of its descendants actually took focus.
    • restoreDefaultFocus

      public boolean restoreDefaultFocus()
      Gives focus to the default-focus view in the view hierarchy that has this view as a root. If the default-focus view cannot be found, falls back to calling requestFocus(int).
      Returns:
      Whether this view or one of its descendants actually took focus
    • requestFocus

      public final boolean requestFocus(int direction)
      Call this to try to give focus to a specific view or to one of its descendants and give it a hint about what direction focus is heading.

      A view will not actually take focus if it is not focusable (isFocusable() returns false), or if it is focusable, and it is not focusable in touch mode (isFocusableInTouchMode()) while the device is in touch mode.

      See also focusSearch(int), which is what you call to say that you have focus, and you want your parent to look for the next one.

      This is equivalent to calling requestFocus(int, Rect) with null set for the previously focused rectangle.

      Parameters:
      direction - One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
      Returns:
      Whether this view or one of its descendants actually took focus.
    • requestFocus

      public boolean requestFocus(int direction, @Nullable Rect previouslyFocusedRect)
      Call this to try to give focus to a specific view or to one of its descendants and give it hints about the direction and a specific rectangle that the focus is coming from. The rectangle can help give larger views a finer grained hint about where focus is coming from, and therefore, where to show selection, or forward focus change internally.

      A view will not actually take focus if it is not focusable (isFocusable() returns false), or if it is focusable and it is not focusable in touch mode (isFocusableInTouchMode()) while the device is in touch mode.

      A View will not take focus if it is not visible.

      A View will not take focus if one of its parents has ViewGroup.getDescendantFocusability() equal to ViewGroup.FOCUS_BLOCK_DESCENDANTS.

      See also focusSearch(int), which is what you call to say that you have focus, and you want your parent to look for the next one.

      You may wish to override this method if your custom View has an internal View that it wishes to forward the request to.

      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 this view or one of its descendants actually took focus.
    • setFocusedInCluster

      @Internal public final void setFocusedInCluster()
      Sets this View as the one which receives focus the next time cluster navigation jumps to the cluster containing this View. This does NOT change focus even if the cluster containing this view is current.
    • setRevealOnFocusHint

      public final void setRevealOnFocusHint(boolean revealOnFocus)
      Sets this view's preference for reveal behavior when it gains focus.

      When set to true, this is a signal to ancestor views in the hierarchy that this view would prefer to be brought fully into view when it gains focus. For example, a text field that a user is meant to type into. Other views such as scrolling containers may prefer to opt-out of this behavior.

      The default value for views is true, though subclasses may change this based on their preferred behavior.

      Parameters:
      revealOnFocus - true to request reveal on focus in ancestors, false otherwise
      See Also:
    • getRevealOnFocusHint

      public final boolean getRevealOnFocusHint()
      Returns this view's preference for reveal behavior when it gains focus.

      When this method returns true for a child view requesting focus, ancestor views responding to a focus change in ViewParent.requestChildFocus(View, View) should make a best effort to make the newly focused child fully visible to the user. When it returns false, ancestor views should preferably not disrupt scroll positioning or other properties affecting visibility to the user as part of the focus change.

      Returns:
      true if this view would prefer to become fully visible when it gains focus, false if it would prefer not to disrupt scroll positioning
      See Also:
    • requestRectangleOnScreen

      public boolean requestRectangleOnScreen(Rect rectangle)
      Request that a rectangle of this view be visible on the screen, scrolling if necessary just enough.

      A View should call this if it maintains some notion of which part of its content is interesting. For example, a text editing view should call this when its cursor moves.

      The Rectangle passed into this method should be in the View's content coordinate space. It should not be affected by which part of the View is currently visible or its scroll position.

      Parameters:
      rectangle - The rectangle in the View's content coordinate space
      Returns:
      Whether any parent scrolled.
    • requestRectangleOnScreen

      public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate)
      Request that a rectangle of this view be visible on the screen, scrolling if necessary just enough.

      A View should call this if it maintains some notion of which part of its content is interesting. For example, a text editing view should call this when its cursor moves.

      The Rectangle passed into this method should be in the View's content coordinate space. It should not be affected by which part of the View is currently visible or its scroll position.

      When immediate is set to true, scrolling will not be animated.

      Parameters:
      rectangle - The rectangle in the View's content coordinate space
      immediate - True to forbid animated scrolling, false otherwise
      Returns:
      Whether any parent scrolled.
    • isFocusedByDefault

      public final boolean isFocusedByDefault()
      Returns whether this View should receive focus when the focus is restored for the view hierarchy containing this view.

      Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a window or serves as a target of cluster navigation.

      Returns:
      true if this view is the default-focus view, false otherwise
      See Also:
    • setFocusedByDefault

      public void setFocusedByDefault(boolean isFocusedByDefault)
      Sets whether this View should receive focus when the focus is restored for the view hierarchy containing this view.

      Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a window or serves as a target of cluster navigation.

      Parameters:
      isFocusedByDefault - true to set this view as the default-focus view, false otherwise.
      See Also:
    • keyboardNavigationClusterSearch

      public View keyboardNavigationClusterSearch(View currentCluster, int direction)
      Find the nearest keyboard navigation cluster in the specified direction. This does not actually give focus to that cluster.
      Parameters:
      currentCluster - The starting point of the search. Null means the current cluster is not found yet
      direction - Direction to look
      Returns:
      The nearest keyboard navigation cluster in the specified direction, or null if none can be found
    • clearFocus

      public void clearFocus()
      Called when this view wants to give up focus. If focus is cleared onFocusChanged(boolean, int, Rect) is called.

      Note: When not in touch-mode, the framework will try to give focus to the first focusable View from the top after focus is cleared. Hence, if this View is the first from the top that can take focus, then all callbacks related to clearing focus will be invoked after which the framework will give focus to this view.

    • hasFocus

      public boolean hasFocus()
      Returns true if this view has focus itself, or is the ancestor of the view that has focus.
      Returns:
      True if this view has or contains focus, false otherwise.
    • hasFocusable

      public final boolean hasFocusable()
      Returns true if this view is focusable or if it contains a reachable View for which this method returns true. A "reachable hasFocusable()" is a view whose parents do not block descendants focus. Only VISIBLE views are considered focusable.
      Returns:
      true if the view is focusable or if the view contains a focusable view, false otherwise
      See Also:
    • hasExplicitFocusable

      public final boolean hasExplicitFocusable()
      Returns true if this view is focusable or if it contains a reachable View for which this method returns true. A "reachable hasExplicitFocusable()" is a view whose parents do not block descendants focus. Only VISIBLE views for which getFocusable() would return FOCUSABLE are considered focusable.
      Returns:
      true if the view is focusable or if the view contains a focusable view, false otherwise
      See Also:
    • onFocusChanged

      @CallSuper protected void onFocusChanged(boolean gainFocus, int direction, @Nullable Rect previouslyFocusedRect)
      Called by the view system when the focus state of this view changes. When the focus change event is caused by directional navigation, direction and previouslyFocusedRect provide insight into where the focus is coming from. When overriding, be sure to call up through to the super class so that the standard focus handling will occur.
      Parameters:
      gainFocus - True if the View has focus; false otherwise.
      direction - The direction focus has moved when requestFocus() is called to give this view focus. Values are FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, or FOCUS_BACKWARD. It may not always apply, in which case use the default.
      previouslyFocusedRect - The rectangle, in this view's coordinate system, of the previously focused view. If applicable, this will be passed in as finer grained information about where the focus is coming from (in addition to direction). Will be null otherwise.
    • isFocused

      public boolean isFocused()
      Returns true if this view has focus
      Returns:
      True if this view has focus, false otherwise.
    • findFocus

      @Nullable public View findFocus()
      Find the view in the hierarchy rooted at this view that currently has focus.
      Returns:
      The view that currently has focus, or null if no focused view can be found.
    • focusSearch

      @Nullable public View focusSearch(int direction)
      Find the nearest view in the specified direction that can take focus. This does not actually give focus to that view.
      Parameters:
      direction - One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
      Returns:
      The nearest focusable in the specified direction, or null if none can be found.
    • isKeyboardNavigationCluster

      public final boolean isKeyboardNavigationCluster()
      Returns whether this View is a root of a keyboard navigation cluster.
      Returns:
      True if this view is a root of a cluster, or false otherwise.
    • setKeyboardNavigationCluster

      public void setKeyboardNavigationCluster(boolean isCluster)
      Set whether this view is a root of a keyboard navigation cluster.
      Parameters:
      isCluster - If true, this view is a root of a cluster.
    • getNextFocusLeftId

      public int getNextFocusLeftId()
      Gets the id of the view to use when the next focus is FOCUS_LEFT.
      Returns:
      The next focus ID, or NO_ID if the framework should decide automatically.
    • setNextFocusLeftId

      public void setNextFocusLeftId(int nextFocusLeftId)
      Sets the id of the view to use when the next focus is FOCUS_LEFT.
      Parameters:
      nextFocusLeftId - The next focus ID, or NO_ID if the framework should decide automatically.
    • getNextFocusRightId

      public int getNextFocusRightId()
      Gets the id of the view to use when the next focus is FOCUS_RIGHT.
      Returns:
      The next focus ID, or NO_ID if the framework should decide automatically.
    • setNextFocusRightId

      public void setNextFocusRightId(int nextFocusRightId)
      Sets the id of the view to use when the next focus is FOCUS_RIGHT.
      Parameters:
      nextFocusRightId - The next focus ID, or NO_ID if the framework should decide automatically.
    • getNextFocusUpId

      public int getNextFocusUpId()
      Gets the id of the view to use when the next focus is FOCUS_UP.
      Returns:
      The next focus ID, or NO_ID if the framework should decide automatically.
    • setNextFocusUpId

      public void setNextFocusUpId(int nextFocusUpId)
      Sets the id of the view to use when the next focus is FOCUS_UP.
      Parameters:
      nextFocusUpId - The next focus ID, or NO_ID if the framework should decide automatically.
    • getNextFocusDownId

      public int getNextFocusDownId()
      Gets the id of the view to use when the next focus is FOCUS_DOWN.
      Returns:
      The next focus ID, or NO_ID if the framework should decide automatically.
    • setNextFocusDownId

      public void setNextFocusDownId(int nextFocusDownId)
      Sets the id of the view to use when the next focus is FOCUS_DOWN.
      Parameters:
      nextFocusDownId - The next focus ID, or NO_ID if the framework should decide automatically.
    • getNextFocusForwardId

      public int getNextFocusForwardId()
      Gets the id of the view to use when the next focus is FOCUS_FORWARD.
      Returns:
      The next focus ID, or NO_ID if the framework should decide automatically.
    • setNextFocusForwardId

      public void setNextFocusForwardId(int nextFocusForwardId)
      Sets the id of the view to use when the next focus is FOCUS_FORWARD.
      Parameters:
      nextFocusForwardId - The next focus ID, or NO_ID if the framework should decide automatically.
    • getNextClusterForwardId

      public int getNextClusterForwardId()
      Gets the id of the root of the next keyboard navigation cluster.
      Returns:
      The next keyboard navigation cluster ID, or NO_ID if the framework should decide automatically.
    • setNextClusterForwardId

      public void setNextClusterForwardId(int nextClusterForwardId)
      Sets the id of the view to use as the root of the next keyboard navigation cluster.
      Parameters:
      nextClusterForwardId - The next cluster ID, or NO_ID if the framework should decide automatically.
    • isShown

      public boolean isShown()
      Returns the visibility of this view and all of its ancestors
      Returns:
      True if this view and all of its ancestors are VISIBLE
    • setHorizontalScrollBarEnabled

      public void setHorizontalScrollBarEnabled(boolean enabled)
      Define whether the horizontal scrollbar should have or not.
      Parameters:
      enabled - true if the horizontal scrollbar should be enabled
      See Also:
    • setVerticalScrollBarEnabled

      public void setVerticalScrollBarEnabled(boolean enabled)
      Define whether the vertical scrollbar should have or not.
      Parameters:
      enabled - true if the vertical scrollbar should be enabled
      See Also:
    • isHorizontalScrollBarEnabled

      public boolean isHorizontalScrollBarEnabled()
      Indicate whether the horizontal scrollbar should have or not.
      Returns:
      true if the horizontal scrollbar already created, false otherwise
      See Also:
    • isVerticalScrollBarEnabled

      public boolean isVerticalScrollBarEnabled()
      Indicate whether the vertical scrollbar should have or not.
      Returns:
      true if the vertical scrollbar already created, false otherwise
      See Also:
    • setScrollbarFadingEnabled

      public void setScrollbarFadingEnabled(boolean fadeScrollbars)
      Define whether scrollbars will fade when the view is not scrolling.
      Parameters:
      fadeScrollbars - whether to enable fading
    • isScrollbarFadingEnabled

      public boolean isScrollbarFadingEnabled()
      Returns true if scrollbars will fade when this view is not scrolling
      Returns:
      true if scrollbar fading is enabled
    • getScrollBarDefaultDelayBeforeFade

      public int getScrollBarDefaultDelayBeforeFade()
      Returns the delay before scrollbars fade.
      Returns:
      the delay before scrollbars fade
    • setScrollBarDefaultDelayBeforeFade

      public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade)
      Define the delay before scrollbars fade.
      Parameters:
      scrollBarDefaultDelayBeforeFade - - the delay before scrollbars fade
    • getScrollBarFadeDuration

      public int getScrollBarFadeDuration()
      Returns the scrollbar fade duration.
      Returns:
      the scrollbar fade duration, in milliseconds
    • setScrollBarFadeDuration

      public void setScrollBarFadeDuration(int scrollBarFadeDuration)
      Define the scrollbar fade duration.
      Parameters:
      scrollBarFadeDuration - - the scrollbar fade duration, in milliseconds
    • getScrollBarSize

      public int getScrollBarSize()
      Returns the scrollbar size.
      Returns:
      the scrollbar size
    • setScrollBarSize

      public void setScrollBarSize(int scrollBarSize)
      Define the scrollbar size.
      Parameters:
      scrollBarSize - - the scrollbar size
    • setScrollBarStyle

      public void setScrollBarStyle(int style)

      Specify the style of the scrollbars. The scrollbars can be overlaid or inset. When inset, they add to the padding of the view. And the scrollbars can be drawn inside the padding area or on the edge of the view. For example, if a view has a background drawable and you want to draw the scrollbars inside the padding specified by the drawable, you can use SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to appear at the edge of the view, ignoring the padding, then you can use SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.

      Parameters:
      style - the style of the scrollbars. Should be one of SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
      See Also:
    • getScrollBarStyle

      public int getScrollBarStyle()

      Returns the current scrollbar style.

      Returns:
      the current scrollbar style
      See Also:
    • setVerticalScrollbarThumbDrawable

      public void setVerticalScrollbarThumbDrawable(@Nullable Drawable drawable)
      Defines the vertical scrollbar thumb drawable
      See Also:
    • setVerticalScrollbarTrackDrawable

      public void setVerticalScrollbarTrackDrawable(@Nullable Drawable drawable)
      Defines the vertical scrollbar track drawable
      See Also:
    • setHorizontalScrollbarThumbDrawable

      public void setHorizontalScrollbarThumbDrawable(@Nullable Drawable drawable)
      Defines the horizontal thumb drawable
      See Also:
    • setHorizontalScrollbarTrackDrawable

      public void setHorizontalScrollbarTrackDrawable(@Nullable Drawable drawable)
      Defines the horizontal track drawable
      See Also:
    • getVerticalScrollbarThumbDrawable

      @Nullable public Drawable getVerticalScrollbarThumbDrawable()
      Returns the currently configured Drawable for the thumb of the vertical scroll bar if it exists, null otherwise.
      See Also:
    • getVerticalScrollbarTrackDrawable

      @Nullable public Drawable getVerticalScrollbarTrackDrawable()
      Returns the currently configured Drawable for the track of the vertical scroll bar if it exists, null otherwise.
      See Also:
    • getHorizontalScrollbarThumbDrawable

      @Nullable public Drawable getHorizontalScrollbarThumbDrawable()
      Returns the currently configured Drawable for the thumb of the horizontal scroll bar if it exists, null otherwise.
      See Also:
    • getHorizontalScrollbarTrackDrawable

      @Nullable public Drawable getHorizontalScrollbarTrackDrawable()
      Returns the currently configured Drawable for the track of the horizontal scroll bar if it exists, null otherwise.
      See Also:
    • scrollTo

      public void scrollTo(int x, int y)
      Set the scrolled position of your view. This will cause a call to onScrollChanged(int, int, int, int) and the view will be invalidated.
      Parameters:
      x - the x position to scroll to
      y - the y position to scroll to
    • scrollBy

      public void scrollBy(int x, int y)
      Move the scrolled position of your view. This will cause a call to onScrollChanged(int, int, int, int) and the view will be invalidated.
      Parameters:
      x - the amount of pixels to scroll by horizontally
      y - the amount of pixels to scroll by vertically
    • awakenScrollBars

      protected final boolean awakenScrollBars()

      Trigger the scrollbars to draw. When invoked this method starts an animation to fade the scrollbars out after a default delay. If a subclass provides animated scrolling, the start delay should equal the duration of the scrolling animation.

      The animation starts only if at least one of the scrollbars is enabled, as specified by isHorizontalScrollBarEnabled() and isVerticalScrollBarEnabled(). When the animation is started, this method returns true, and false otherwise. If the animation is started, this method calls invalidate(); in that case the caller should not call invalidate().

      This method should be invoked every time a subclass directly updates the scroll parameters.

      This method is automatically invoked by scrollBy(int, int) and scrollTo(int, int).

      Returns:
      true if the animation is played, false otherwise
      See Also:
    • awakenScrollBars

      protected boolean awakenScrollBars(int startDelay)

      Trigger the scrollbars to draw. When invoked this method starts an animation to fade the scrollbars out after a fixed delay. If a subclass provides animated scrolling, the start delay should equal the duration of the scrolling animation.

      The animation starts only if at least one of the scrollbars is enabled, as specified by isHorizontalScrollBarEnabled() and isVerticalScrollBarEnabled(). When the animation is started, this method returns true, and false otherwise. If the animation is started, this method calls invalidate(); in that case the caller should not call invalidate().

      This method should be invoked every time a subclass directly updates the scroll parameters.

      Parameters:
      startDelay - the delay, in milliseconds, after which the animation should start; when the delay is 0, the animation starts immediately
      Returns:
      true if the animation is played, false otherwise
      See Also:
    • setScrollX

      public void setScrollX(int value)
      Set the horizontal scrolled position of your view. This will cause a call to onScrollChanged(int, int, int, int) and the view will be invalidated.
      Parameters:
      value - the x position to scroll to
    • setScrollY

      public void setScrollY(int value)
      Set the vertical scrolled position of your view. This will cause a call to onScrollChanged(int, int, int, int) and the view will be invalidated.
      Parameters:
      value - the y position to scroll to
    • getScrollX

      public final int getScrollX()
      Return the scrolled left position of this view. This is the left edge of the displayed part of your view. You do not need to draw any pixels farther left, since those are outside the frame of your view on screen.
      Returns:
      The left edge of the displayed part of your view, in pixels.
    • getScrollY

      public final int getScrollY()
      Return the scrolled top position of this view. This is the top edge of the displayed part of your view. You do not need to draw any pixels above it, since those are outside the frame of your view on screen.
      Returns:
      The top edge of the displayed part of your view, in pixels.
    • computeHorizontalScrollRange

      protected int computeHorizontalScrollRange()

      Compute the horizontal range that the horizontal scrollbar represents.

      The range is expressed in arbitrary units that must be the same as the units used by computeHorizontalScrollExtent() and computeHorizontalScrollOffset().

      The default range is the drawing width of this view.

      Returns:
      the total horizontal range represented by the horizontal scrollbar
      See Also:
    • computeHorizontalScrollOffset

      protected int computeHorizontalScrollOffset()

      Compute the horizontal offset of the horizontal 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 computeHorizontalScrollRange() and computeHorizontalScrollExtent().

      The default offset is the scroll offset of this view.

      Returns:
      the horizontal offset of the scrollbar's thumb
      See Also:
    • computeHorizontalScrollExtent

      protected int computeHorizontalScrollExtent()

      Compute the horizontal extent of the horizontal scrollbar's thumb within the horizontal range. This value is used to compute the length 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 computeHorizontalScrollRange() and computeHorizontalScrollOffset().

      The default extent is the drawing width of this view.

      Returns:
      the horizontal extent of the scrollbar's thumb
      See Also:
    • computeVerticalScrollRange

      protected int computeVerticalScrollRange()

      Compute the vertical range that the vertical scrollbar represents.

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

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

      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 computeVerticalScrollRange() and computeVerticalScrollExtent().

      The default offset is the scroll offset of this view.

      Returns:
      the vertical offset of the scrollbar's thumb
      See Also:
    • computeVerticalScrollExtent

      protected int computeVerticalScrollExtent()

      Compute the vertical extent of the vertical scrollbar's thumb within the vertical range. This value is used to compute the length 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 computeVerticalScrollRange() and computeVerticalScrollOffset().

      The default extent is the drawing height of this view.

      Returns:
      the vertical extent of the scrollbar's thumb
      See Also:
    • canScrollHorizontally

      public boolean canScrollHorizontally(int direction)
      Check if this view can be scrolled horizontally in a certain direction.
      Parameters:
      direction - Negative to check scrolling left, positive to check scrolling right.
      Returns:
      true if this view can be scrolled in the specified direction, false otherwise.
    • canScrollVertically

      public boolean canScrollVertically(int direction)
      Check if this view can be scrolled vertically in a certain direction.
      Parameters:
      direction - Negative to check scrolling up, positive to check scrolling down.
      Returns:
      true if this view can be scrolled in the specified direction, false otherwise.
    • isVerticalScrollBarHidden

      @Internal protected boolean isVerticalScrollBarHidden()
      Override this if the vertical scrollbar needs to be hidden in a subclass, like when FastScroller is visible.
      Returns:
      whether to temporarily hide the vertical scrollbar
    • setScrollIndicators

      public void setScrollIndicators(int indicators)
      Sets the state of all scroll indicators.

      See setScrollIndicators(int, int) for usage information.

      Parameters:
      indicators - a bitmask of indicators that should be enabled, or 0 to disable all indicators
      See Also:
    • setScrollIndicators

      public void setScrollIndicators(int indicators, int mask)
      Sets the state of the scroll indicators specified by the mask. To change all scroll indicators at once, see setScrollIndicators(int).

      When a scroll indicator is enabled, it will be displayed if the view can scroll in the direction of the indicator.

      Multiple indicator types may be enabled or disabled by passing the logical OR of the desired types. If multiple types are specified, they will all be set to the same enabled state.

      Parameters:
      indicators - the indicator direction, or the logical OR of multiple indicator directions. One or more of:
      See Also:
    • getScrollIndicators

      public int getScrollIndicators()
      Returns a bitmask representing the enabled scroll indicators.

      For example, if the top and left scroll indicators are enabled and all other indicators are disabled, the return value will be View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT.

      To check whether the bottom scroll indicator is enabled, use the value of (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0.

      Returns:
      a bitmask representing the enabled scroll indicators
    • getVerticalScrollbarWidth

      public int getVerticalScrollbarWidth()
      Returns the width of the vertical scrollbar.
      Returns:
      The width in pixels of the vertical scrollbar or 0 if there is no vertical scrollbar.
    • getHorizontalScrollbarHeight

      protected int getHorizontalScrollbarHeight()
      Returns the height of the horizontal scrollbar.
      Returns:
      The height in pixels of the horizontal scrollbar or 0 if there is no horizontal scrollbar.
    • getVerticalFadingEdgeLength

      public int getVerticalFadingEdgeLength()
      Returns the size of the vertical faded edges used to indicate that more content in this view is visible.
      Returns:
      The size in pixels of the vertical faded edge or 0 if vertical faded edges are not enabled for this view.
    • computeScroll

      public void computeScroll()
      Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary. This will typically be done if the child is animating a scroll using a Scroller.
    • isHorizontalFadingEdgeEnabled

      public boolean isHorizontalFadingEdgeEnabled()

      Indicate whether the horizontal edges are faded when the view is scrolled horizontally.

      Returns:
      true if the horizontal edges should are faded on scroll, false otherwise
      See Also:
    • setHorizontalFadingEdgeEnabled

      public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled)

      Define whether the horizontal edges should be faded when this view is scrolled horizontally.

      Parameters:
      horizontalFadingEdgeEnabled - true if the horizontal edges should be faded when the view is scrolled horizontally
      See Also:
    • isVerticalFadingEdgeEnabled

      public boolean isVerticalFadingEdgeEnabled()

      Indicate whether the vertical edges are faded when the view is scrolled horizontally.

      Returns:
      true if the vertical edges should are faded on scroll, false otherwise
      See Also:
    • setVerticalFadingEdgeEnabled

      public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled)

      Define whether the vertical edges should be faded when this view is scrolled vertically.

      Parameters:
      verticalFadingEdgeEnabled - true if the vertical edges should be faded when the view is scrolled vertically
      See Also:
    • getFadingEdge

      @Internal public int getFadingEdge()
      Get the fading edge flags, used for inspection.
      Returns:
      One of FADING_EDGE_NONE, FADING_EDGE_VERTICAL, or FADING_EDGE_HORIZONTAL
    • getFadingEdgeLength

      @Internal public int getFadingEdgeLength()
      Get the fading edge length, used for inspection
      Returns:
      The fading edge length or 0
    • onScrollChanged

      protected void onScrollChanged(int l, int t, int oldl, int oldt)
      This is called in response to an internal scroll in this view (i.e., the view scrolled its own contents). This is typically as a result of scrollBy(int, int) or scrollTo(int, int) having been called.
      Parameters:
      l - Current horizontal scroll origin.
      t - Current vertical scroll origin.
      oldl - Previous horizontal scroll origin.
      oldt - Previous vertical scroll origin.
    • overScrollBy

      protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent)
      Scroll the view with standard behavior for scrolling beyond the normal content boundaries. Views that call this method should override onOverScrolled(int, int, boolean, boolean) to respond to the results of an over-scroll operation.

      Views can use this method to handle any touch or fling-based scrolling.

      Parameters:
      deltaX - Change in X in pixels
      deltaY - Change in Y in pixels
      scrollX - Current X scroll value in pixels before applying deltaX
      scrollY - Current Y scroll value in pixels before applying deltaY
      scrollRangeX - Maximum content scroll range along the X axis
      scrollRangeY - Maximum content scroll range along the Y axis
      maxOverScrollX - Number of pixels to overscroll by in either direction along the X axis.
      maxOverScrollY - Number of pixels to overscroll by in either direction along the Y axis.
      isTouchEvent - true if this scroll operation is the result of a touch event.
      Returns:
      true if scrolling was clamped to an over-scroll boundary along either axis, false otherwise.
    • onOverScrolled

      protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY)
      Called by overScrollBy(int, int, int, int, int, int, int, int, boolean) to respond to the results of an over-scroll operation.
      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
    • getOverScrollMode

      public int getOverScrollMode()
      Returns the over-scroll mode for this view. The result will be one of OVER_SCROLL_ALWAYS, OVER_SCROLL_IF_CONTENT_SCROLLS (allow over-scrolling only if the view content is larger than the container), or OVER_SCROLL_NEVER.
      Returns:
      This view's over-scroll mode.
    • setOverScrollMode

      public void setOverScrollMode(int overScrollMode)
      Set the over-scroll mode for this view. Valid over-scroll modes are OVER_SCROLL_ALWAYS, OVER_SCROLL_IF_CONTENT_SCROLLS (allow over-scrolling only if the view content is larger than the container), or OVER_SCROLL_NEVER.

      Setting the over-scroll mode of a view will have an effect only if the view is capable of scrolling.

      Parameters:
      overScrollMode - The new over-scroll mode for this view.
    • setNestedScrollingEnabled

      public void setNestedScrollingEnabled(boolean enabled)
      Enable or disable nested scrolling for this view.

      If this property is set to true the view will be permitted to initiate nested scrolling operations with a compatible parent view in the current hierarchy. If this view does not implement nested scrolling this will have no effect. Disabling nested scrolling while a nested scroll is in progress has the effect of stopping the nested scroll.

      Parameters:
      enabled - true to enable nested scrolling, false to disable
      See Also:
    • isNestedScrollingEnabled

      public boolean isNestedScrollingEnabled()
      Returns true if nested scrolling is enabled for this view.

      If nested scrolling is enabled and this View class implementation supports it, this view will act as a nested scrolling child view when applicable, forwarding data about the scroll operation in progress to a compatible and cooperating nested scrolling parent.

      Returns:
      true if nested scrolling is enabled
      See Also:
    • startNestedScroll

      public boolean startNestedScroll(int axes, int type)
      Begin a nestable scroll operation along the given axes, for the given input type.

      A view starting a nested scroll promises to abide by the following contract:

      The view will call startNestedScroll upon initiating a scroll operation. In the case of a touch scroll type this corresponds to the initial MotionEvent.ACTION_DOWN. In the case of touch scrolling the nested scroll will be terminated automatically in the same manner as ViewParent.requestDisallowInterceptTouchEvent(boolean). In the event of programmatic scrolling the caller must explicitly call stopNestedScroll(int) to indicate the end of the nested scroll.

      If startNestedScroll returns true, a cooperative parent was found. If it returns false the caller may ignore the rest of this contract until the next scroll. Calling startNestedScroll while a nested scroll is already in progress will return true.

      At each incremental step of the scroll the caller should invoke dispatchNestedPreScroll once it has calculated the requested scrolling delta. If it returns true the nested scrolling parent at least partially consumed the scroll and the caller should adjust the amount it scrolls by.

      After applying the remainder of the scroll delta the caller should invoke dispatchNestedScroll, passing both the delta consumed and the delta unconsumed. A nested scrolling parent may treat these values differently. See ViewParent.onNestedScroll(View, int, int, int, int, int, int[]).

      Parameters:
      axes - Flags consisting of a combination of SCROLL_AXIS_HORIZONTAL and/or SCROLL_AXIS_VERTICAL.
      type - the type of input which cause this scroll event
      Returns:
      true if a cooperative parent was found and nested scrolling has been enabled for the current gesture.
      See Also:
    • stopNestedScroll

      public void stopNestedScroll(int type)
      Stop a nested scroll in progress for the given input type.

      Calling this method when a nested scroll is not currently in progress is harmless.

      Parameters:
      type - the type of input which cause this scroll event
      See Also:
    • hasNestedScrollingParent

      public boolean hasNestedScrollingParent(int type)
      Returns true if this view has a nested scrolling parent for the given input type.

      The presence of a nested scrolling parent indicates that this view has initiated a nested scroll and it was accepted by an ancestor view further up the view hierarchy.

      Parameters:
      type - the type of input which cause this scroll event
      Returns:
      whether this view has a nested scrolling parent
    • dispatchNestedScroll

      public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, @Nullable int[] offsetInWindow, int type, @NonNull int[] consumed)
      Dispatch one step of a nested scroll in progress.

      Implementations of views that support nested scrolling should call this to report info about a scroll in progress to the current nested scrolling parent. If a nested scroll is not currently in progress or nested scrolling is not enabled for this view this method does nothing.

      Compatible View implementations should also call dispatchNestedPreScroll before consuming a component of the scroll event themselves.

      The original nested scrolling child (where the input events were received to start the scroll) must provide a non-null consumed parameter with values {0, 0}.

      Parameters:
      dxConsumed - Horizontal distance in pixels consumed by this view during this scroll step
      dyConsumed - Vertical distance in pixels consumed by this view during this scroll step
      dxUnconsumed - Horizontal scroll distance in pixels not consumed by this view
      dyUnconsumed - Horizontal scroll distance in pixels not consumed by this view
      offsetInWindow - Optional. If not null, on return this will contain the offset in local view coordinates of this view from before this operation to after it completes. View implementations may use this to adjust expected input coordinate tracking.
      type - the type of input which cause this scroll event
      consumed - Output. Upon this method returning, will contain the original values plus any scroll distances consumed by all of this view's nested scrolling parents up the view hierarchy. Index 0 for the x dimension, and index 1 for the y dimension
      Returns:
      true if the event was dispatched, false if it could not be dispatched.
      See Also:
    • dispatchNestedPreScroll

      public boolean dispatchNestedPreScroll(int dx, int dy, @Nullable int[] consumed, @Nullable int[] offsetInWindow, int type)
      Dispatch one step of a nested scroll in progress before this view consumes any portion of it.

      Nested pre-scroll events are to nested scroll events what touch intercept is to touch. dispatchNestedPreScroll offers an opportunity for the parent view in a nested scrolling operation to consume some or all of the scroll operation before the child view consumes it.

      Parameters:
      dx - Horizontal scroll distance in pixels
      dy - Vertical scroll distance in pixels
      consumed - Output. If not null, consumed[0] will contain the consumed component of dx and consumed[1] the consumed dy.
      offsetInWindow - Optional. If not null, on return this will contain the offset in local view coordinates of this view from before this operation to after it completes. View implementations may use this to adjust expected input coordinate tracking.
      type - the type of input which cause this scroll event
      Returns:
      true if the parent consumed some or all of the scroll delta
      See Also:
    • dispatchNestedFling

      public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed)
      Dispatch a fling to a nested scrolling parent.

      This method should be used to indicate 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.

      Parameters:
      velocityX - Horizontal fling velocity in pixels per second
      velocityY - Vertical fling velocity in pixels per second
      consumed - true if the child consumed the fling, false otherwise
      Returns:
      true if the nested scrolling parent consumed or otherwise reacted to the fling
    • dispatchNestedPreFling

      public boolean dispatchNestedPreFling(float velocityX, float velocityY)
      Dispatch a fling to a nested scrolling parent before it is processed by this view.

      Nested pre-fling events are to nested fling events what touch intercept is to touch and what nested pre-scroll is to nested scroll. dispatchNestedPreFling offsets an opportunity for the parent view in a nested fling to fully consume the fling before the child view consumes it. If this method returns true, a nested parent view consumed the fling and this view should not scroll as a result.

      For a better user experience, only one view in a nested scrolling chain should consume the fling at a time. If a parent view consumed the fling this method will return false. Custom view implementations should account for this in two ways:

      • If a custom view is paged and needs to settle to a fixed page-point, do not call dispatchNestedPreFling; consume the fling and settle to a valid position regardless.
      • If a nested parent does consume the fling, this view should not scroll at all, even to settle back to a valid idle position.

      Views should also not offer fling velocities to nested parent views along an axis where scrolling is not currently supported; a ScrollView should not offer a horizontal fling velocity to its parents since scrolling along that axis is not permitted and carrying velocity along that motion does not make sense.

      Parameters:
      velocityX - Horizontal fling velocity in pixels per second
      velocityY - Vertical fling velocity in pixels per second
      Returns:
      true if a nested scrolling parent consumed the fling
    • getWidth

      public final int getWidth()
      Get the width of the view.
      Returns:
      the width in pixels
    • getHeight

      public final int getHeight()
      Get the height of the view.
      Returns:
      the height in pixels
    • getDrawingRect

      public void getDrawingRect(@NonNull Rect outRect)
      Return the visible drawing bounds of your view. Fills in the output rectangle with the values from getScrollX(), getScrollY(), getWidth(), and getHeight(). These bounds do not account for any transformation properties currently set on the view, such as setScaleX(float) or setRotation(float).
      Parameters:
      outRect - The (scrolled) drawing bounds of the view.
    • getLeft

      public final int getLeft()
      Left position of this view relative to its parent.
      Returns:
      The left edge of this view, in pixels.
    • setLeft

      public final void setLeft(int left)
      Sets the left position of this view relative to its parent. This method is meant to be called by the layout system and should not generally be called otherwise, because the property may be changed at any time by the layout.
      Parameters:
      left - The left of this view, in pixels.
    • getTop

      public final int getTop()
      Top position of this view relative to its parent.
      Returns:
      The top of this view, in pixels.
    • setTop

      public final void setTop(int top)
      Sets the top position of this view relative to its parent. This method is meant to be called by the layout system and should not generally be called otherwise, because the property may be changed at any time by the layout.
      Parameters:
      top - The top of this view, in pixels.
    • getRight

      public final int getRight()
      Right position of this view relative to its parent.
      Returns:
      The right edge of this view, in pixels.
    • setRight

      public final void setRight(int right)
      Sets the right position of this view relative to its parent. This method is meant to be called by the layout system and should not generally be called otherwise, because the property may be changed at any time by the layout.
      Parameters:
      right - The right of this view, in pixels.
    • getBottom

      public final int getBottom()
      Bottom position of this view relative to its parent.
      Returns:
      The bottom of this view, in pixels.
    • setBottom

      public final void setBottom(int bottom)
      Sets the bottom position of this view relative to its parent. This method is meant to be called by the layout system and should not generally be called otherwise, because the property may be changed at any time by the layout.
      Parameters:
      bottom - The bottom of this view, in pixels.
    • getMatrix

      public final Matrix getMatrix()
      The transform matrix of this view, which is calculated based on the current rotation, scale, and pivot properties. This will affect this view logically (such as for events) and visually.

      Note that the matrix should be only used as read-only (like transforming coordinates). In that case, you should call hasIdentityMatrix() first to check if the operation can be skipped, because this method will return null if not available. However, if you want to change the transform matrix, you should use methods such as setTranslationX(float). The return value may be null, indicating that it is identity.

      Returns:
      the current transform matrix for the view, may be null if identity
      See Also:
    • getInverseMatrix

      public final Matrix getInverseMatrix()
      Utility method to retrieve the inverse of the current matrix property. Note that the matrix should be only used as read-only (like transforming coordinates).
      Returns:
      The inverse of the current matrix of this view, may be null if identity
      See Also:
    • hasIdentityMatrix

      public final boolean hasIdentityMatrix()
      Returns true if the transform matrix is the identity matrix.
      Returns:
      true if the transform matrix is the identity matrix, false otherwise.
      See Also:
    • getX

      public float getX()
      The visual x position of this view, in pixels. This is equivalent to the translationX property plus the current left property.
      Returns:
      The visual x position of this view, in pixels.
    • setX

      public void setX(float x)
      Sets the visual x position of this view, in pixels. This is equivalent to setting the translationX property to be the difference between the x value passed in and the current left property.
      Parameters:
      x - The visual x position of this view, in pixels.
    • getY

      public float getY()
      The visual y position of this view, in pixels. This is equivalent to the translationY property plus the current top property.
      Returns:
      The visual y position of this view, in pixels.
    • setY

      public void setY(float y)
      Sets the visual y position of this view, in pixels. This is equivalent to setting the translationY property to be the difference between the y value passed in and the current top property.
      Parameters:
      y - The visual y position of this view, in pixels.
    • getZ

      public float getZ()
      The visual z position of this view, in pixels. This is equivalent to the translationZ property plus the current elevation property.
      Returns:
      The visual z position of this view, in pixels.
    • setZ

      public void setZ(float z)
      Sets the visual z position of this view, in pixels. This is equivalent to setting the translationZ property to be the difference between the z value passed in and the current elevation property.
      Parameters:
      z - The visual z position of this view, in pixels.
    • getElevation

      public float getElevation()
      The base elevation of this view relative to its parent, in pixels.
      Returns:
      The base depth position of the view, in pixels.
    • setElevation

      public void setElevation(float elevation)
      Sets the base elevation of this view, in pixels.
    • getTranslationX

      public float getTranslationX()
      The horizontal location of this view relative to its left position. This position is post-layout, in addition to wherever the object's layout placed it.
      Returns:
      The horizontal position of this view relative to its left position, in pixels.
    • setTranslationX

      public void setTranslationX(float translationX)
      Sets the horizontal location of this view relative to its left position. This effectively positions the object post-layout, in addition to wherever the object's layout placed it. This is not used for transition animation.
      Parameters:
      translationX - The horizontal position of this view relative to its left position, in pixels.
    • getTranslationY

      public float getTranslationY()
      The vertical location of this view relative to its top position. This position is post-layout, in addition to wherever the object's layout placed it.
      Returns:
      The vertical position of this view relative to its top position, in pixels.
    • setTranslationY

      public void setTranslationY(float translationY)
      Sets the vertical location of this view relative to its top position. This effectively positions the object post-layout, in addition to wherever the object's layout placed it.
      Parameters:
      translationY - The vertical position of this view relative to its top position, in pixels.
    • getTranslationZ

      public float getTranslationZ()
      The depth location of this view relative to its elevation.
      Returns:
      The depth of this view relative to its elevation.
    • setTranslationZ

      public void setTranslationZ(float translationZ)
      Sets the depth location of this view relative to its elevation.
    • getRotation

      public float getRotation()
      The degrees that the view is rotated around the pivot point.
      Returns:
      The degrees of rotation.
      See Also:
    • setRotation

      public void setRotation(float rotation)
      Sets the degrees that the view is rotated around the pivot point. Increasing values result in clockwise rotation.
      Parameters:
      rotation - The degrees of rotation.
      See Also:
    • getRotationY

      public float getRotationY()
      The degrees that the view is rotated around the vertical axis through the pivot point.
      Returns:
      The degrees of Y rotation.
      See Also:
    • setRotationY

      public void setRotationY(float rotationY)
      Sets the degrees that the view is rotated around the vertical axis through the pivot point. Increasing values result in counter-clockwise rotation from the viewpoint of looking down the y-axis.
      Parameters:
      rotationY - The degrees of Y rotation.
      See Also:
    • getRotationX

      public float getRotationX()
      The degrees that the view is rotated around the horizontal axis through the pivot point.
      Returns:
      The degrees of X rotation.
      See Also:
    • setRotationX

      public void setRotationX(float rotationX)
      Sets the degrees that the view is rotated around the horizontal axis through the pivot point. Increasing values result in clockwise rotation from the viewpoint of looking down the x-axis.
      Parameters:
      rotationX - The degrees of X rotation.
      See Also:
    • getScaleX

      public float getScaleX()
      The amount that the view is scaled in x around the pivot point, as a proportion of the view's unscaled width. A value of 1, the default, means that no scaling is applied.

      By default, this is 1.0f.

      Returns:
      The scaling factor.
      See Also:
    • setScaleX

      public void setScaleX(float scaleX)
      Sets the amount that the view is scaled in x around the pivot point, as a proportion of the view's unscaled width. A value of 1 means that no scaling is applied.
      Parameters:
      scaleX - The scaling factor.
      See Also:
    • getScaleY

      public float getScaleY()
      The amount that the view is scaled in y around the pivot point, as a proportion of the view's unscaled height. A value of 1, the default, means that no scaling is applied.

      By default, this is 1.0f.

      Returns:
      The scaling factor.
      See Also:
    • setScaleY

      public void setScaleY(float scaleY)
      Sets the amount that the view is scaled in Y around the pivot point, as a proportion of the view's unscaled width. A value of 1 means that no scaling is applied.
      Parameters:
      scaleY - The scaling factor.
      See Also:
    • getPivotX

      public float getPivotX()
      The x location of the point around which the view is rotated and scaled.
      Returns:
      The x location of the pivot point.
      See Also:
    • setPivotX

      public void setPivotX(float pivotX)
      Sets the x location of the point around which the view is rotated and scaled. By default, the pivot point is centered on the object. Setting this property disables this behavior and causes the view to use only the explicitly set pivotX and pivotY values.
      Parameters:
      pivotX - The x location of the pivot point.
      See Also:
    • getPivotY

      public float getPivotY()
      The y location of the point around which the view is rotated and scaled.
      Returns:
      The y location of the pivot point.
      See Also:
    • setPivotY

      public void setPivotY(float pivotY)
      Sets the y location of the point around which the view is rotated and scaled. By default, the pivot point is centered on the object. Setting this property disables this behavior and causes the view to use only the explicitly set pivotX and pivotY values.
      Parameters:
      pivotY - The y location of the pivot point.
      See Also:
    • isPivotSet

      public boolean isPivotSet()
      Returns whether a pivot has been set by a call to setPivotX(float) or setPivotY(float). If no pivot has been set then the pivot will be the center of the view.
      Returns:
      True if a pivot has been set, false if the default pivot is being used
    • resetPivot

      public void resetPivot()
      Clears any pivot previously set by a call to setPivotX(float) or setPivotY(float). After calling this isPivotSet() will be false and the pivot used for rotation will return to default of being centered on the view.
    • getAlpha

      public float getAlpha()
      The opacity of the view. This is a value from 0 to 1, where 0 means the view is completely transparent and 1 means the view is completely opaque.

      By default this is 1.0f.

      Returns:
      The opacity of the view.
    • forceHasOverlappingRendering

      public void forceHasOverlappingRendering(boolean hasOverlappingRendering)
      Sets the behavior for overlapping rendering for this view (see hasOverlappingRendering() for more details on this behavior). Calling this method is an alternative to overriding hasOverlappingRendering() in a subclass, providing the value which is then used internally. That is, when this method is called, the value of hasOverlappingRendering() is ignored and the value passed into this method is used instead.
      Parameters:
      hasOverlappingRendering - The value for overlapping rendering to be used internally instead of that returned by hasOverlappingRendering().
    • getHasOverlappingRendering

      public final boolean getHasOverlappingRendering()
      Returns the value for overlapping rendering that is used internally. This is either the value passed into forceHasOverlappingRendering(boolean), if called, or the return value of hasOverlappingRendering(), otherwise.
      Returns:
      The value for overlapping rendering being used internally.
    • hasOverlappingRendering

      public boolean hasOverlappingRendering()
      Returns whether this View has content which overlaps.

      This function, intended to be overridden by specific View types, is an optimization when alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer and then composited into place, which can be expensive. If the view has no overlapping rendering, the view can draw each primitive with the appropriate alpha value directly. An example of overlapping rendering is a TextView with a background image, such as a Button. An example of non-overlapping rendering is a TextView with no background, or an ImageView with only the foreground image. The default implementation returns true; subclasses should override if they have cases which can be optimized.

      Note: The return value of this method is ignored if forceHasOverlappingRendering(boolean) has been called on this view.

      Returns:
      true if the content in this view might overlap, false otherwise.
    • setAlpha

      public void setAlpha(float alpha)
    • setTransitionAlpha

      public final void setTransitionAlpha(float alpha)
      This property is intended only for use by the Fade transition, which animates it to produce a visual translucency that does not side effect (or get affected by) the real alpha property. This value is composited with the other alpha value (and the AlphaAnimation value, when that is present) to produce a final visual translucency result, which is what is passed into the DisplayList.
    • getTransitionAlpha

      public final float getTransitionAlpha()
      This property is intended only for use by the Fade transition, which animates it to produce a visual translucency that does not side effect (or get affected by) the real alpha property. This value is composited with the other alpha value (and the AlphaAnimation value, when that is present) to produce a final visual translucency result, which is what is passed into the DisplayList.
    • setAnimationMatrix

      public final void setAnimationMatrix(@Nullable Matrix matrix)
      Changes the transformation matrix on the view. This is used in animation frameworks, such as Transition. When the animation finishes, the matrix should be cleared by calling this method with null as the matrix parameter. Application developers should use transformation methods like setRotation(float), setScaleX(float), setScaleX(float), setTranslationX(float)} and setTranslationY(float) instead.
      Parameters:
      matrix - The matrix, null indicates that the matrix should be cleared.
      See Also:
    • getAnimationMatrix

      @Nullable public final Matrix getAnimationMatrix()
      Changes the transition matrix on the view. This is only used in the transition animation framework, Transition. Returns null when there is no transformation provided by setAnimationMatrix(Matrix).

      Note that this matrix only affects the visual effect of this view, you should never call this method. You should use methods such as setTranslationX(float)} instead to change the transformation logically.

      Returns:
      the matrix, null indicates that the matrix should be cleared.
      See Also:
    • getStateListAnimator

      public StateListAnimator getStateListAnimator()
      Returns the current StateListAnimator if exists.
      Returns:
      StateListAnimator or null if it does not exist
      See Also:
    • setStateListAnimator

      public void setStateListAnimator(@Nullable StateListAnimator stateListAnimator)
      Attaches the provided StateListAnimator to this View.

      Any previously attached StateListAnimator will be detached.

      Parameters:
      stateListAnimator - The StateListAnimator to update the view
      See Also:
    • onAttachedToWindow

      @CallSuper protected void onAttachedToWindow()
      This is called when the view is attached to a window. At this point it has a Surface and will start drawing. Note that this function is guaranteed to be called before onDraw(Canvas), however it may be called any time before the first onDraw -- including before or after onMeasure(int, int).
      See Also:
    • onDetachedFromWindow

      protected void onDetachedFromWindow()
      This is called when the view is detached from a window. At this point it no longer has a surface for drawing.
      See Also:
    • isAttachedToWindow

      public boolean isAttachedToWindow()
      Returns true if this view is currently attached to a window.
    • getWindowAttachCount

      protected int getWindowAttachCount()
      Returns:
      The number of times this view has been attached to a window
    • hasTransientState

      public boolean hasTransientState()
      Indicates whether the view is currently tracking transient state that the app should not need to concern itself with saving and restoring, but that the framework should take special note to preserve when possible.

      A view with transient state cannot be trivially rebound from an external data source, such as an adapter binding item views in a list. This may be because the view is performing an animation, tracking user selection of content, or similar.

      Returns:
      true if the view has transient state
    • setHasTransientState

      public void setHasTransientState(boolean hasTransientState)
      Set whether this view is currently tracking transient state that the framework should attempt to preserve when possible. This flag is reference counted, so every call to setHasTransientState(true) should be paired with a later call to setHasTransientState(false).

      A view with transient state cannot be trivially rebound from an external data source, such as an adapter binding item views in a list. This may be because the view is performing an animation, tracking user selection of content, or similar.

      Parameters:
      hasTransientState - true if this view has transient state
    • setHasTranslationTransientState

      @Internal public void setHasTranslationTransientState(boolean hasTranslationTransientState)
      Set the view is tracking translation transient state. This flag is used to check if the view need to call setHasTransientState(false) to reset transient state that set when starting translation.
      Parameters:
      hasTranslationTransientState - true if this view has translation transient state
    • hasTranslationTransientState

      @Internal public boolean hasTranslationTransientState()
    • cancelPendingInputEvents

      public final void cancelPendingInputEvents()
      Cancel any deferred high-level input events that were previously posted to the event queue.

      Many views post high-level events such as click handlers to the event queue to run deferred in order to preserve a desired user experience - clearing visible pressed states before executing, etc. This method will abort any events of this nature that are currently in flight.

      Custom views that generate their own high-level deferred input events should override onCancelPendingInputEvents() and remove those pending events from the queue.

      This will also cancel pending input events for any child views.

      Note that this may not be sufficient as a debouncing strategy for clicks in all cases. This will not impact newer events posted after this call that may occur as a result of lower-level input events still waiting in the queue. If you are trying to prevent double-submitted events for the duration of some sort of asynchronous transaction you should also take other steps to protect against unexpected double inputs e.g. calling setEnabled(false) and re-enabling the view when the transaction completes, tracking already submitted transaction IDs, etc.

    • onCancelPendingInputEvents

      public void onCancelPendingInputEvents()
      Called as the result of a call to cancelPendingInputEvents() on this view or a parent view.

      This method is responsible for removing any pending high-level input events that were posted to the event queue to run later. Custom view classes that post their own deferred high-level events via post(Runnable), postDelayed(Runnable, long) or Handler should override this method, call super.onCancelPendingInputEvents() and remove those callbacks as appropriate.

    • setDuplicateParentStateEnabled

      public void setDuplicateParentStateEnabled(boolean enabled)

      Enables or disables the duplication of the parent's state into this view. When duplication is enabled, this view gets its drawable state from its parent rather than from its own internal properties.

      Note: in the current implementation, setting this property to true after the view was added to a ViewGroup might have no effect at all. This property should always be used from XML or set to true before adding this view to a ViewGroup.

      Note: if this view's parent addStateFromChildren property is enabled and this property is enabled, an exception will be thrown.

      Note: if the child view uses and updates additional states which are unknown to the parent, these states should not be affected by this method.

      Parameters:
      enabled - True to enable duplication of the parent's drawable state, false to disable it.
      See Also:
    • isDuplicateParentStateEnabled

      public boolean isDuplicateParentStateEnabled()

      Indicates whether this duplicates its drawable state from its parent.

      Returns:
      True if this view's drawable state is duplicated from the parent, false otherwise
      See Also:
    • isLaidOut

      public boolean isLaidOut()
      Returns true if this view has been through at least one layout since it was last attached to or detached from a window.
    • setWillNotDraw

      public void setWillNotDraw(boolean willNotDraw)
      If this view doesn't do any drawing on its own, set this flag to allow further optimizations. By default, this flag is not set on View, but could be set on some View subclasses such as ViewGroup.

      Typically, if you override onDraw(Canvas) you should clear this flag.

      Parameters:
      willNotDraw - whether this View draw on its own
    • willNotDraw

      public boolean willNotDraw()
      Returns whether this View draws on its own.
      Returns:
      true if this view has nothing to draw, false otherwise
    • setSoundEffectsEnabled

      public void setSoundEffectsEnabled(boolean soundEffectsEnabled)
      Set whether this view should have sound effects enabled for events such as clicking and touching.

      You may wish to disable sound effects for a view if you already play sounds, for instance, a dial key that plays dtmf tones.

      Parameters:
      soundEffectsEnabled - whether sound effects are enabled for this view.
      See Also:
    • isSoundEffectsEnabled

      public boolean isSoundEffectsEnabled()
      Returns:
      whether this view should have sound effects enabled for events such as clicking and touching.
      See Also:
    • setHapticFeedbackEnabled

      public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled)
      Set whether this view should have haptic feedback for events such as long presses.

      You may wish to disable haptic feedback if your view already controls its own haptic feedback.

      Parameters:
      hapticFeedbackEnabled - whether haptic feedback enabled for this view.
      See Also:
    • isHapticFeedbackEnabled

      public boolean isHapticFeedbackEnabled()
      Returns:
      whether this view should have haptic feedback enabled for events long presses.
      See Also:
    • playSoundEffect

      public void playSoundEffect(int soundConstant)
      Play a sound effect for this view.

      The framework will play sound effects for some built in actions, such as clicking, but you may wish to play these effects in your widget, for instance, for internal navigation.

      The sound effect will only be played if sound effects are enabled by the user, and isSoundEffectsEnabled() is true.

      Parameters:
      soundConstant - One of the constants defined in SoundEffectConstants.
    • performHapticFeedback

      public final boolean performHapticFeedback(int feedbackConstant)
      BZZZTT!!1!

      Provide haptic feedback to the user for this view.

      The framework will provide haptic feedback for some built in actions, such as long presses, but you may wish to provide feedback for your own widget.

      The feedback will only be performed if isHapticFeedbackEnabled() is true.

      Parameters:
      feedbackConstant - One of the constants defined in HapticFeedbackConstants
    • performHapticFeedback

      public boolean performHapticFeedback(int feedbackConstant, int flags)
      BZZZTT!!1!

      Like performHapticFeedback(int), with additional options.

      Parameters:
      feedbackConstant - One of the constants defined in HapticFeedbackConstants
      flags - Additional flags as per HapticFeedbackConstants.
    • getRawLayoutDirection

      @Internal public final int getRawLayoutDirection()
      Returns the layout direction for this view.
      Returns:
      One of LAYOUT_DIRECTION_LTR, LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT or LAYOUT_DIRECTION_LOCALE.
    • setLayoutDirection

      public void setLayoutDirection(int layoutDirection)
      Set the layout direction for this view. This will propagate a reset of layout direction resolution to the view's children and resolve layout direction for this view.

      Should be one of:

      LAYOUT_DIRECTION_LTR, LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE.

      Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution proceeds up the parent chain of the view to get the value. If there is no parent, then it will return the default LAYOUT_DIRECTION_LTR.

      Parameters:
      layoutDirection - the layout direction to set
    • getLayoutDirection

      public final int getLayoutDirection()
      Returns the resolved layout direction for this view.
      Returns:
      LAYOUT_DIRECTION_RTL if the layout direction is RTL or returns LAYOUT_DIRECTION_LTR if the layout direction is not RTL.
    • isLayoutRtl

      @Internal public final boolean isLayoutRtl()
      Indicates whether this view's layout is right-to-left. This is resolved from layout attribute and/or the inherited value from the parent
      Returns:
      true if the layout is right-to-left.
    • resolveRtlPropertiesIfNeeded

      @Internal public boolean resolveRtlPropertiesIfNeeded()
      Resolve all RTL related properties.
      Returns:
      true if resolution of RTL properties has been done
    • onRtlPropertiesChanged

      protected void onRtlPropertiesChanged(int layoutDirection)
      Called 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.

      Parameters:
      layoutDirection - the direction of the layout
      See Also:
    • resolveLayoutDirection

      @Internal public boolean resolveLayoutDirection()
      Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing that the parent directionality can and will be resolved before its children.
      Returns:
      true if resolution has been done, false otherwise.
    • canResolveLayoutDirection

      public final boolean canResolveLayoutDirection()
      Check if layout direction resolution can be done.
      Returns:
      true if layout direction resolution can be done otherwise return false.
    • isLayoutDirectionInherited

      @Internal public final boolean isLayoutDirectionInherited()
      Returns:
      true if the layout direction is inherited.
    • isLayoutDirectionResolved

      public final boolean isLayoutDirectionResolved()
      Returns:
      true if layout direction has been resolved.
    • getRawTextDirection

      @Internal public final int getRawTextDirection()
      Return the value specifying the text direction or policy that was set with setTextDirection(int).
      Returns:
      the defined text direction. It can be one of:

      TEXT_DIRECTION_INHERIT, TEXT_DIRECTION_FIRST_STRONG, TEXT_DIRECTION_ANY_RTL, TEXT_DIRECTION_LTR, TEXT_DIRECTION_RTL, TEXT_DIRECTION_LOCALE, TEXT_DIRECTION_FIRST_STRONG_LTR, TEXT_DIRECTION_FIRST_STRONG_RTL

    • setTextDirection

      public void setTextDirection(int textDirection)
      Set the text direction.

      Should be one of:

      TEXT_DIRECTION_INHERIT, TEXT_DIRECTION_FIRST_STRONG, TEXT_DIRECTION_ANY_RTL, TEXT_DIRECTION_LTR, TEXT_DIRECTION_RTL, TEXT_DIRECTION_LOCALE TEXT_DIRECTION_FIRST_STRONG_LTR, TEXT_DIRECTION_FIRST_STRONG_RTL,

      Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution proceeds up the parent chain of the view to get the value. If there is no parent, then it will return the default TEXT_DIRECTION_FIRST_STRONG.

      Parameters:
      textDirection - the direction to set.
    • getTextDirection

      public final int getTextDirection()
      Return the resolved text direction.
      Returns:
      the resolved text direction. Returns one of:

      TEXT_DIRECTION_FIRST_STRONG, TEXT_DIRECTION_ANY_RTL, TEXT_DIRECTION_LTR, TEXT_DIRECTION_RTL, TEXT_DIRECTION_LOCALE, TEXT_DIRECTION_FIRST_STRONG_LTR, TEXT_DIRECTION_FIRST_STRONG_RTL

    • resolveTextDirection

      @Internal public boolean resolveTextDirection()
      Resolve the text direction.
      Returns:
      true if resolution has been done, false otherwise.
    • canResolveTextDirection

      public final boolean canResolveTextDirection()
      Check if text direction resolution can be done.
      Returns:
      true if text direction resolution can be done otherwise return false.
    • isTextDirectionInherited

      @Internal public final boolean isTextDirectionInherited()
      Returns:
      true if text direction is inherited.
    • isTextDirectionResolved

      public final boolean isTextDirectionResolved()
      Returns:
      true if text direction is resolved.
    • getRawTextAlignment

      @Internal public final int getRawTextAlignment()
      Return the value specifying the text alignment or policy that was set with setTextAlignment(int).
      Returns:
      the defined text alignment. It can be one of:

      TEXT_ALIGNMENT_INHERIT, TEXT_ALIGNMENT_GRAVITY, TEXT_ALIGNMENT_CENTER, TEXT_ALIGNMENT_TEXT_START, TEXT_ALIGNMENT_TEXT_END, TEXT_ALIGNMENT_VIEW_START, TEXT_ALIGNMENT_VIEW_END

    • setTextAlignment

      public void setTextAlignment(int textAlignment)
      Set the text alignment.

      Should be one of

      TEXT_ALIGNMENT_INHERIT, TEXT_ALIGNMENT_GRAVITY, TEXT_ALIGNMENT_CENTER, TEXT_ALIGNMENT_TEXT_START, TEXT_ALIGNMENT_TEXT_END, TEXT_ALIGNMENT_VIEW_START, TEXT_ALIGNMENT_VIEW_END

      Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution proceeds up the parent chain of the view to get the value. If there is no parent, then it will return the default TEXT_ALIGNMENT_GRAVITY.

      Parameters:
      textAlignment - The text alignment to set.
    • getTextAlignment

      public final int getTextAlignment()
      Return the resolved text alignment.
      Returns:
      the resolved text alignment. Returns one of:

      TEXT_ALIGNMENT_GRAVITY, TEXT_ALIGNMENT_CENTER, TEXT_ALIGNMENT_TEXT_START, TEXT_ALIGNMENT_TEXT_END, TEXT_ALIGNMENT_VIEW_START, TEXT_ALIGNMENT_VIEW_END

    • resolveTextAlignment

      @Internal public boolean resolveTextAlignment()
      Resolve the text alignment.
      Returns:
      true if resolution has been done, false otherwise.
    • canResolveTextAlignment

      public final boolean canResolveTextAlignment()
      Check if text alignment resolution can be done.
      Returns:
      true if text alignment resolution can be done otherwise return false.
    • isTextAlignmentInherited

      @Internal public final boolean isTextAlignmentInherited()
      Returns:
      true if text alignment is inherited.
    • isTextAlignmentResolved

      public final boolean isTextAlignmentResolved()
      Returns:
      true if text alignment is resolved.
    • resolvePadding

      @Internal public void resolvePadding()
      Resolves padding depending on layout direction, if applicable, and recomputes internal padding values to adjust for scroll bars.
    • getBaseline

      public int getBaseline()

      Return the offset of the widget's text baseline from the widget's top boundary. If this widget does not support baseline alignment, this method returns -1.

      Returns:
      the offset of the baseline within the widget's bounds or -1 if baseline alignment is not supported
    • isInLayout

      public final boolean isInLayout()
      Returns whether the view hierarchy is currently undergoing a layout pass. This information is useful to avoid situations such as calling requestLayout() during a layout pass.
      Returns:
      whether the view hierarchy is currently undergoing a layout pass
    • requestLayout

      @CallSuper public void requestLayout()
      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 (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.

    • isLayoutRequested

      public boolean isLayoutRequested()

      Indicates whether or not this view's layout will be requested during the next hierarchy layout pass.

      Returns:
      true if the layout will be forced during next layout pass
    • forceLayout

      public void forceLayout()
      Forces this view to be laid out during the next layout pass. This method does not call requestLayout() or forceLayout() on the parent.
    • drawableHotspotChanged

      @CallSuper public void drawableHotspotChanged(float x, float y)
      This function is called whenever the view hotspot changes and needs to be propagated to drawables or child views managed by the view.

      Dispatching to child views is handled by dispatchDrawableHotspotChanged(float, float).

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

      Parameters:
      x - hotspot x coordinate
      y - hotspot y coordinate
    • dispatchDrawableHotspotChanged

      public void dispatchDrawableHotspotChanged(float x, float y)
      Dispatches drawableHotspotChanged to all of this View's children.
      Parameters:
      x - hotspot x coordinate
      y - hotspot y coordinate
      See Also:
    • refreshDrawableState

      public void refreshDrawableState()
      Call this to force a view to update its drawable state. This will cause drawableStateChanged to be called on this view. Views that are interested in the new state should call getDrawableState.
      See Also:
    • resolveDrawables

      @Internal protected void resolveDrawables()
      Resolve the Drawables depending on the layout direction. This is implicitly supposing that the View directionality can and will be resolved before its Drawables.

      Will call onResolveDrawables(int) when resolution is done.

    • onResolveDrawables

      @Internal public void onResolveDrawables(int layoutDirection)
      Called when layout direction has been resolved.

      The default implementation does nothing.

      Parameters:
      layoutDirection - The resolved layout direction.
      See Also:
    • resetResolvedDrawables

      @Internal protected void resetResolvedDrawables()
    • setPadding

      public void setPadding(int left, int top, int right, int bottom)
      Sets the padding. The view may add on the space required to display the scrollbars, depending on the style and visibility of the scrollbars. So the values returned from getPaddingLeft(), getPaddingTop(), getPaddingRight() and getPaddingBottom() may be different from the values set in this call.
      Parameters:
      left - the left padding in pixels
      top - the top padding in pixels
      right - the right padding in pixels
      bottom - the bottom padding in pixels
    • internalSetPadding

      @Internal protected void internalSetPadding(int left, int top, int right, int bottom)
    • setPaddingRelative

      public void setPaddingRelative(int start, int top, int end, int bottom)
      Sets the relative padding. The view may add on the space required to display the scrollbars, depending on the style and visibility of the scrollbars. So the values returned from getPaddingStart(), getPaddingTop(), getPaddingEnd() and getPaddingBottom() may be different from the values set in this call.
      Parameters:
      start - the start padding in pixels
      top - the top padding in pixels
      end - the end padding in pixels
      bottom - the bottom padding in pixels
    • getPaddingTop

      public int getPaddingTop()
      Returns the top padding of this view.
      Returns:
      the top padding in pixels
    • getPaddingBottom

      public int getPaddingBottom()
      Returns the bottom padding of this view. If there are inset and enabled scrollbars, this value may include the space required to display the scrollbars as well.
      Returns:
      the bottom padding in pixels
    • getPaddingLeft

      public int getPaddingLeft()
      Returns the left padding of this view. If there are inset and enabled scrollbars, this value may include the space required to display the scrollbars as well.
      Returns:
      the left padding in pixels
    • getPaddingStart

      public int getPaddingStart()
      Returns the start padding of this view depending on its resolved layout direction. If there are inset and enabled scrollbars, this value may include the space required to display the scrollbars as well.
      Returns:
      the start padding in pixels
    • getPaddingRight

      public int getPaddingRight()
      Returns the right padding of this view. If there are inset and enabled scrollbars, this value may include the space required to display the scrollbars as well.
      Returns:
      the right padding in pixels
    • getPaddingEnd

      public int getPaddingEnd()
      Returns the end padding of this view depending on its resolved layout direction. If there are inset and enabled scrollbars, this value may include the space required to display the scrollbars as well.
      Returns:
      the end padding in pixels
    • isPaddingRelative

      public boolean isPaddingRelative()
      Return if the padding has been set through relative values setPaddingRelative(int, int, int, int) or through
      Returns:
      true if the padding is relative or false if it is not.
    • verifyDrawable

      @CallSuper protected boolean verifyDrawable(@NonNull 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. This allows animations for those drawables to be scheduled.

      Be sure to call through to the super class when overriding this function.

      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

      @CallSuper protected void drawableStateChanged()
      This function is called whenever the state of the view changes in such a way that it impacts the state of drawables being shown.

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

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

      See Also:
    • getDrawableState

      public final int[] getDrawableState()
      Return an array of resource IDs of the drawable states representing the current state of the view.
      Returns:
      The current drawable state
      See Also:
    • onCreateDrawableState

      @NonNull protected int[] onCreateDrawableState(int extraSpace)
      Generate the new Drawable state for this view. This is called by the view system when the cached Drawable state is determined to be invalid. To retrieve the current state, you should use getDrawableState().
      Parameters:
      extraSpace - if non-zero, this is the number of extra entries you would like in the returned array in which you can place your own states.
      Returns:
      an array holding the current Drawable state of the view.
      See Also:
    • mergeDrawableStates

      @NonNull protected static int[] mergeDrawableStates(@NonNull int[] baseState, @NonNull int[] additionalState)
      Merge your own state values in additionalState into the base state values baseState that were returned by onCreateDrawableState(int).
      Parameters:
      baseState - The base state values returned by onCreateDrawableState(int), which will be modified to also hold your own additional state values.
      additionalState - The additional state values you would like added to baseState; this array is not modified.
      Returns:
      As a convenience, the baseState array you originally passed into the function is returned.
      See Also:
    • jumpDrawablesToCurrentState

      @CallSuper public void jumpDrawablesToCurrentState()
      Call Drawable.jumpToCurrentState() on all Drawable objects associated with this view.

      Also calls StateListAnimator.jumpToCurrentState() if there is a StateListAnimator attached to this view.

    • setBackground

      public void setBackground(@Nullable Drawable background)
      Set the background to a given Drawable, or remove the background. If the background has padding, this View's padding is set to the background's padding. However, when a background is removed, this View's padding isn't touched.
      Parameters:
      background - The Drawable to use as the background, or null to remove the background
    • getBackground

      @Nullable public Drawable getBackground()
      Gets the background drawable
      Returns:
      The drawable used as the background for this view, if any.
      See Also:
    • getForeground

      @Nullable public Drawable getForeground()
      Returns the drawable used as the foreground of this View. The foreground drawable, if non-null, is always drawn on top of the view's content.
      Returns:
      a Drawable or null if no foreground was set
      See Also:
    • setForeground

      public void setForeground(@Nullable Drawable foreground)
      Supply a Drawable that is to be rendered on top of all of the content in the view.
      Parameters:
      foreground - the Drawable to be drawn on top of the children
    • isForegroundInsidePadding

      @Internal public boolean isForegroundInsidePadding()
      Magic bit used to support features of framework-internal window decor implementation details. This used to live exclusively in FrameLayout.
      Returns:
      true if the foreground should draw inside the padding region or false if it should draw inset by the view's padding
    • getForegroundGravity

      public int getForegroundGravity()
      Describes how the foreground is positioned.
      Returns:
      foreground gravity.
      See Also:
    • setForegroundGravity

      public void setForegroundGravity(int gravity)
      Describes how the foreground is positioned. Defaults to START and TOP.
      Parameters:
      gravity - see Gravity
      See Also:
    • getViewTreeObserver

      @NonNull public final ViewTreeObserver getViewTreeObserver()
      Returns the ViewTreeObserver for this view's hierarchy. The view tree observer can be used to get notifications when global events, like layout, happen.

      The returned ViewTreeObserver observer is not guaranteed to remain valid for the lifetime of this View. If the caller of this method keeps a long-lived reference to ViewTreeObserver, it should always check for the return value of ViewTreeObserver.isAlive().

      Returns:
      The ViewTreeObserver for this view's hierarchy.
    • getRootView

      public final View getRootView()
      Finds the topmost view in the current view hierarchy.
      Returns:
      the topmost view containing this view
    • toGlobalMotionEvent

      @Internal public boolean toGlobalMotionEvent(@NonNull MotionEvent ev)
      Transforms a motion event from view-local coordinates to on-screen coordinates.
      Parameters:
      ev - the view-local motion event
      Returns:
      false if the transformation could not be applied
    • toLocalMotionEvent

      @Internal public boolean toLocalMotionEvent(@NonNull MotionEvent ev)
      Transforms a motion event from on-screen coordinates to view-local coordinates.
      Parameters:
      ev - the on-screen motion event
      Returns:
      false if the transformation could not be applied
    • transformMatrixToGlobal

      public void transformMatrixToGlobal(@NonNull Matrix matrix)
      Modifies the input matrix such that it maps view-local coordinates to on-screen coordinates.
      Parameters:
      matrix - input matrix to modify
    • transformMatrixToLocal

      public void transformMatrixToLocal(@NonNull Matrix matrix)
      Modifies the input matrix such that it maps on-screen coordinates to view-local coordinates.
      Parameters:
      matrix - input matrix to modify
    • getBoundsOnScreen

      public void getBoundsOnScreen(@NonNull Rect outRect)
      Gets the location of this view in screen coordinates.
      Parameters:
      outRect - The output location
    • getBoundsOnScreen

      public void getBoundsOnScreen(@NonNull Rect outRect, boolean clipToParent)
      Gets the location of this view in screen coordinates.
      Parameters:
      outRect - The output location
      clipToParent - Whether to clip child bounds to the parent ones.
    • mapRectFromViewToScreenCoords

      public void mapRectFromViewToScreenCoords(@NonNull RectF rect, boolean clipToParent)
      Map a rectangle from view-relative coordinates to screen-relative coordinates
      Parameters:
      rect - The rectangle to be mapped
      clipToParent - Whether to clip child bounds to the parent ones.
    • getLocationOnScreen

      public void getLocationOnScreen(int[] outLocation)

      Computes the coordinates of this view on the screen. The argument must be an array of two integers. After the method returns, the array contains the x and y location in that order.

      Parameters:
      outLocation - an array of two integers in which to hold the coordinates
    • getLocationInWindow

      public void getLocationInWindow(@NonNull int[] outLocation)

      Computes the coordinates of this view in its window. The argument must be an array of two integers. After the method returns, the array contains the x and y location in that order.

      Parameters:
      outLocation - an array of two integers in which to hold the coordinates
    • transformFromViewToWindowSpace

      @Internal public void transformFromViewToWindowSpace(@NonNull int[] inOutLocation)
    • findViewById

      @Nullable public final <T extends View> T findViewById(int id)
      Finds the first descendant view with the given ID, the view itself if the ID matches getId(), or null if the ID is invalid (< 0) or there is no matching view in the hierarchy.
      Parameters:
      id - the id to search for
      Returns:
      a view with given id if found, or null otherwise
    • requireViewById

      @NonNull public final <T extends View> T requireViewById(int id)
      Finds the first descendant view with the given ID, the view itself if the ID matches getId(), or results in an error.
      Parameters:
      id - the ID to search for
      Returns:
      a view with given ID
      Throws:
      IllegalArgumentException - the ID is invalid or there is no matching view in the hierarchy
      See Also:
    • findViewTraversal

      @Internal @Nullable protected <T extends View> T findViewTraversal(int id)
      Parameters:
      id - the id of the view to be found
      Returns:
      the view of the specified id, null if cannot be found
    • findViewByPredicate

      @Internal public final <T extends View> T findViewByPredicate(@NonNull Predicate<View> predicate)
      Look for a child view that matches the specified predicate. If this view matches the predicate, return this view.
      Parameters:
      predicate - The predicate to evaluate.
      Returns:
      The first view that matches the predicate or null.
    • findViewByPredicateTraversal

      @Internal @Nullable protected <T extends View> T findViewByPredicateTraversal(@NonNull Predicate<View> predicate, @Nullable View childToSkip)
      Parameters:
      predicate - The predicate to evaluate.
      childToSkip - If not null, ignores this child during the recursive traversal.
      Returns:
      The first view that matches the predicate or null.
    • findViewByPredicateInsideOut

      @Internal @Nullable public final <T extends View> T findViewByPredicateInsideOut(@NonNull View start, Predicate<View> predicate)
      Look for a child view that matches the specified predicate, starting with the specified view and its descendents and then recusively searching the ancestors and siblings of that view until this view is reached.

      This method is useful in cases where the predicate does not match a single unique view (perhaps multiple views use the same id) and we are trying to find the view that is "closest" in scope to the starting view.

      Parameters:
      start - The view to start from.
      predicate - The predicate to evaluate.
      Returns:
      The first view that matches the predicate or null.
    • getHandler

      @Nullable public final Handler getHandler()
      Returns:
      A handler associated with the thread running the View. This handler can be used to pump events in the UI events queue.
    • getViewRoot

      @Nullable public final ViewRoot getViewRoot()
      Gets the view root associated with the View.
      Returns:
      The view root, or null if none.
    • post

      public final boolean post(@NonNull Runnable action)

      Causes the Runnable to be added to the task queue. The runnable will be run on the UI thread.

      Parameters:
      action - the runnable that will be executed.
      Returns:
      true if the runnable was successfully placed in to the queue
      See Also:
    • postDelayed

      public final boolean postDelayed(@NonNull Runnable action, long delayMillis)

      Causes the Runnable to be added to the task queue, to be run after the specified amount of time elapses. The runnable will be run on the UI thread.

      Note that a result of true does not mean the Runnable will be processed -- if the application is shutdown before the delivery time of the message occurs then the message will be dropped.

      Parameters:
      action - the runnable that will be executed.
      delayMillis - the delay (in milliseconds) until the runnable will be executed.
      Returns:
      true if the runnable was successfully placed in to the queue
      See Also:
    • postOnAnimation

      public final void postOnAnimation(@NonNull Runnable action)

      Causes the runnable to execute on the next animation time step. The runnable will be run on the UI thread.

      Parameters:
      action - the runnable that will be executed
      See Also:
    • postOnAnimationDelayed

      public final void postOnAnimationDelayed(@NonNull Runnable action, long delayMillis)

      Causes the Runnable to execute on the next animation time step, after the specified amount of time elapses. The runnable will be run on the UI thread.

      Parameters:
      action - the runnable that will be executed
      delayMillis - the delay (in milliseconds) until the runnable will be executed
      See Also:
    • removeCallbacks

      public final void removeCallbacks(@Nullable Runnable action)

      Removes the specified Runnable from the message queue.

      Parameters:
      action - the runnable to remove from the task handling queue
      See Also:
    • postInvalidate

      public final void postInvalidate()

      Cause an invalidate to happen on a subsequent cycle through the event loop. Use this to invalidate the View from a non-UI thread.

      This method can be invoked from outside of the UI thread only when this View is attached to a window.

      See Also:
    • postInvalidateDelayed

      public final void postInvalidateDelayed(long delayMilliseconds)

      Cause an invalidate to happen on a subsequent cycle through the event loop. Waits for the specified amount of time.

      This method can be invoked from outside of the UI thread only when this View is attached to a window.

      Parameters:
      delayMilliseconds - the duration in milliseconds to delay the invalidation by
      See Also:
    • postInvalidateOnAnimation

      public final void postInvalidateOnAnimation()

      Cause an invalidate to happen on the next animation time step, typically the next display frame.

      This method can be invoked from outside of the UI thread only when this View is attached to a window.

      See Also:
    • startDragAndDrop

      public final boolean startDragAndDrop(@Nullable Object localState, @Nullable View.DragShadow shadow, int flags)
      Starts a drag and drop operation. This method passes a View.DragShadow object to the window system. The system calls View.DragShadow.onDrawShadow(Canvas) to draw the drag shadow itself at proper level.

      Once the system has the drag shadow, it begins the drag and drop operation by sending drag events to all the View objects in all windows that are currently visible. It does this either by calling the View object's drag listener (an implementation of View.OnDragListener.onDrag(View, DragEvent) or by calling the View object's onDragEvent(DragEvent) method. Both are passed a DragEvent object that has a DragEvent.getAction() value of DragEvent.ACTION_DRAG_STARTED.

      Parameters:
      localState - The data to be transferred by the drag and drop operation. It can be in any form, which can not only store the required data, but also let the view identify whether it can accept the followed DragEvent.
      shadow - The shadow object to draw the shadow, null will generate a default shadow.
      flags - Flags, 0 for no flags.
      Returns:
      true if operation successfully started, false means the system was unable to start the operation because of another ongoing operation or some other reasons.
    • onDragEvent

      public boolean onDragEvent(DragEvent event)
      Handle primitive drag event of this view
      Parameters:
      event - the event to be handled
      Returns:
      true if the event was consumed by the view, false otherwise
    • dispatchVisibilityChanged

      protected void dispatchVisibilityChanged(@NonNull View changedView, int visibility)
      Dispatch a view visibility change down the view hierarchy. ViewGroups should override to route to their children.
      Parameters:
      changedView - The view whose visibility changed. Could be 'this' or an ancestor view.
      visibility - The new visibility of changedView: VISIBLE, INVISIBLE or GONE.
    • onVisibilityChanged

      protected void onVisibilityChanged(@NonNull View changedView, int visibility)
      Called when the visibility of the view or an ancestor of the view has changed.
      Parameters:
      changedView - The view whose visibility changed. May be this or an ancestor view.
      visibility - The new visibility, one of VISIBLE, INVISIBLE or GONE.
    • getWindowVisibility

      public final int getWindowVisibility()
      Returns the current visibility of the window this view is attached to (either GONE, INVISIBLE, or VISIBLE).
      Returns:
      Returns the current visibility of the view's window.
    • dispatchWindowVisibilityChanged

      public void dispatchWindowVisibilityChanged(int visibility)
      Dispatch a window visibility change down the view hierarchy. ViewGroups should override to route to their children.
      Parameters:
      visibility - The new visibility of the window.
      See Also:
    • onWindowVisibilityChanged

      protected void onWindowVisibilityChanged(int visibility)
      Called when the window containing has change its visibility (between GONE, INVISIBLE, and VISIBLE). Note that this tells you whether or not your window is being made visible to the window manager; this does not tell you whether or not your window is obscured by other windows on the screen, even if it is itself visible.
      Parameters:
      visibility - The new visibility of the window.
    • onVisibilityAggregated

      @CallSuper public void onVisibilityAggregated(boolean isVisible)
      Called when the user-visibility of this View is potentially affected by a change to this view itself, an ancestor view or the window this view is attached to.
      Parameters:
      isVisible - true if this view and all of its ancestors are VISIBLE and this view's window is also visible
    • dispatchPointerEvent

      public final boolean dispatchPointerEvent(@NonNull MotionEvent event)
      Dispatch a pointer event.

      Dispatches touch related pointer events to onTouchEvent(MotionEvent) and all other events to onGenericMotionEvent(MotionEvent). This separation of concerns reinforces the invariant that onTouchEvent(MotionEvent) is really about touches and should not be expected to handle other pointing device features.

      Parameters:
      event - the motion event to be dispatched.
      Returns:
      true if the event was handled by the view, false otherwise.
    • dispatchWindowFocusChanged

      public void dispatchWindowFocusChanged(boolean hasFocus)
      Called when the window containing this view gains or loses window focus. ViewGroups should override to route to their children.
      Parameters:
      hasFocus - True if the window containing this view now has focus, false otherwise.
    • onWindowFocusChanged

      public void onWindowFocusChanged(boolean hasWindowFocus)
      Called when the window containing this view gains or loses focus. Note that this is separate from view focus: to receive key events, both your view and its window must have focus. If a window is displayed on top of yours that takes input focus, then your own window will lose focus but the view focus will remain unchanged.
      Parameters:
      hasWindowFocus - True if the window containing this view now has focus, false otherwise.
    • hasWindowFocus

      public boolean hasWindowFocus()
      Returns true if this view is in a window that currently has window focus. Note that this is not the same as the view itself having focus.
      Returns:
      True if this view is in a window that currently has window focus.
    • dispatchGenericMotionEvent

      public boolean dispatchGenericMotionEvent(@NonNull MotionEvent event)
      Dispatch a generic motion event.

      Generic motion events with source class pointer are delivered to the view under the pointer. All other generic motion events are delivered to the focused view. Hover events are handled specially and are delivered to onHoverEvent(MotionEvent).

      Generally, this method should not be overridden.

      Parameters:
      event - the event to be dispatched
      Returns:
      true if the event was consumed by the view, false otherwise
    • dispatchHoverEvent

      protected boolean dispatchHoverEvent(@NonNull MotionEvent event)
      Dispatch a hover event.

      Do not call this method directly. Call dispatchGenericMotionEvent(MotionEvent) instead.

      Parameters:
      event - The motion event to be dispatched.
      Returns:
      True if the event was handled by the view, false otherwise.
    • dispatchGenericPointerEvent

      protected boolean dispatchGenericPointerEvent(@NonNull MotionEvent event)
      Dispatch a generic motion event to the view under the first pointer.

      Do not call this method directly. Call dispatchGenericMotionEvent(MotionEvent) instead.

      Parameters:
      event - The motion event to be dispatched.
      Returns:
      True if the event was handled by the view, false otherwise.
    • onGenericMotionEvent

      public boolean onGenericMotionEvent(@NonNull MotionEvent event)
      Implement this method to handle generic motion events.

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

      Parameters:
      event - the generic motion event being processed.
      Returns:
      true if the event was consumed by the view, false otherwise
    • onHoverEvent

      public boolean onHoverEvent(@NonNull MotionEvent event)
      Implement this method to handle hover events.

      This method is called whenever a pointer is hovering into, over, or out of the bounds of a view and the view is not currently being touched. Hover events are represented as pointer events with action MotionEvent.ACTION_HOVER_ENTER, MotionEvent.ACTION_HOVER_MOVE, or MotionEvent.ACTION_HOVER_EXIT.

      • The view receives a hover event with action MotionEvent.ACTION_HOVER_ENTER when the pointer enters the bounds of the view.
      • The view receives a hover event with action MotionEvent.ACTION_HOVER_MOVE when the pointer has already entered the bounds of the view and has moved.
      • The view receives a hover event with action MotionEvent.ACTION_HOVER_EXIT when the pointer has exited the bounds of the view or when the pointer is about to go down due to a button click, tap, or similar user action that causes the view to be touched.

      The view should implement this method to return true to indicate that it is handling the hover event, such as by changing its drawable state.

      The default implementation calls setHovered(boolean) to update the hovered state of the view when a hover enter or hover exit event is received, if the view is enabled and is clickable. The default implementation also sends hover accessibility events.

      Parameters:
      event - The motion event that describes the hover.
      Returns:
      True if the view handled the hover event.
      See Also:
    • isHovered

      public boolean isHovered()
      Returns true if the view is currently hovered.
      Returns:
      True if the view is currently hovered.
      See Also:
    • setHovered

      public void setHovered(boolean hovered)
      Sets whether the view is currently hovered.

      Calling this method also changes the drawable state of the view. This enables the view to react to hover by using different drawable resources to change its appearance.

      The onHoverChanged(boolean) method is called when the hovered state changes.

      Parameters:
      hovered - True if the view is hovered.
      See Also:
    • onHoverChanged

      public void onHoverChanged(boolean hovered)
      Implement this method to handle hover state changes.

      This method is called whenever the hover state changes as a result of a call to setHovered(boolean).

      Parameters:
      hovered - The current hover state, as returned by isHovered().
      See Also:
    • setOnScrollChangeListener

      public void setOnScrollChangeListener(@Nullable View.OnScrollChangeListener l)
      Register a callback to be invoked when the scroll X or Y positions of this view change.

      Note: Some views handle scrolling independently of View and may have their own separate listeners for scroll-type events.

      Parameters:
      l - The listener to notify when the scroll X or Y position changes.
      See Also:
    • setOnFocusChangeListener

      public void setOnFocusChangeListener(@Nullable View.OnFocusChangeListener l)
      Register a callback to be invoked when focus of this view changed.
      Parameters:
      l - The callback that will run.
    • addOnLayoutChangeListener

      public void addOnLayoutChangeListener(@NonNull View.OnLayoutChangeListener listener)
      Add a listener that will be called when the bounds of the view change due to layout processing.
      Parameters:
      listener - The listener that will be called when layout bounds change.
    • removeOnLayoutChangeListener

      public void removeOnLayoutChangeListener(@NonNull View.OnLayoutChangeListener listener)
      Remove a listener for layout changes.
      Parameters:
      listener - The listener for layout bounds change.
    • addOnAttachStateChangeListener

      public void addOnAttachStateChangeListener(@NonNull View.OnAttachStateChangeListener listener)
      Add a listener for attach state changes.

      This listener will be called whenever this view is attached or detached from a window. Remove the listener using removeOnAttachStateChangeListener(OnAttachStateChangeListener).

      Parameters:
      listener - Listener to attach
      See Also:
    • removeOnAttachStateChangeListener

      public void removeOnAttachStateChangeListener(@NonNull View.OnAttachStateChangeListener listener)
      Remove a listener for attach state changes. The listener will receive no further notification of window attach/detach events.
      Parameters:
      listener - Listener to remove
      See Also:
    • getOnFocusChangeListener

      @Nullable public View.OnFocusChangeListener getOnFocusChangeListener()
      Returns the focus-change callback registered for this view.
      Returns:
      The callback, or null if one is not registered.
    • setOnClickListener

      public void setOnClickListener(@Nullable View.OnClickListener l)
      Register a callback to be invoked when this view is clicked. If this view is not clickable, it becomes clickable.
      Parameters:
      l - The callback that will run
      See Also:
    • hasOnClickListeners

      public boolean hasOnClickListeners()
      Return whether this view has an attached OnClickListener. Returns true if there is a listener, false if there is none.
    • setOnLongClickListener

      public void setOnLongClickListener(@Nullable View.OnLongClickListener l)
      Register a callback to be invoked when this view is clicked and held. If this view is not long clickable, it becomes long clickable.
      Parameters:
      l - The callback that will run
      See Also:
    • hasOnLongClickListeners

      public boolean hasOnLongClickListeners()
      Return whether this view has an attached OnLongClickListener. Returns true if there is a listener, false if there is none.
    • getOnLongClickListener

      @Internal @Nullable public View.OnLongClickListener getOnLongClickListener()
      Returns:
      the registered View.OnLongClickListener if there is one, null otherwise.
    • setOnContextClickListener

      public void setOnContextClickListener(@Nullable View.OnContextClickListener l)
      Register a callback to be invoked when this view is context clicked. If the view is not context clickable, it becomes context clickable.
      Parameters:
      l - The callback that will run
      See Also:
    • setOnCreateContextMenuListener

      public void setOnCreateContextMenuListener(@Nullable View.OnCreateContextMenuListener l)
      Register a callback to be invoked when the context menu for this view is being built. If this view is not long clickable, it becomes long clickable.
      Parameters:
      l - The callback that will run
    • setOnKeyListener

      public void setOnKeyListener(@Nullable View.OnKeyListener l)
      Register a callback to be invoked when a hardware key is pressed in this view. Key presses in software input methods will generally not trigger the methods of this listener.
      Parameters:
      l - the key listener to attach to this view
    • setOnTouchListener

      public void setOnTouchListener(@Nullable View.OnTouchListener l)
      Register a callback to be invoked when a touch event is sent to this view.
      Parameters:
      l - the touch listener to attach to this view
    • setOnGenericMotionListener

      public void setOnGenericMotionListener(@Nullable View.OnGenericMotionListener l)
      Register a callback to be invoked when a generic motion event is sent to this view.
      Parameters:
      l - the generic motion listener to attach to this view
    • setOnHoverListener

      public void setOnHoverListener(@Nullable View.OnHoverListener l)
      Register a callback to be invoked when a hover event is sent to this view.
      Parameters:
      l - the hover listener to attach to this view
    • setOnDragListener

      public void setOnDragListener(@Nullable View.OnDragListener l)
      Register a drag event listener callback object for this View. The parameter is an implementation of View.OnDragListener. To send a drag event to a View, the system calls the View.OnDragListener.onDrag(View, DragEvent) method.
      Parameters:
      l - An implementation of View.OnDragListener.
    • canReceivePointerEvents

      protected boolean canReceivePointerEvents()
      Returns whether this view can receive pointer events.
      Returns:
      true if this view can receive pointer events.
    • dispatchTouchEvent

      public boolean dispatchTouchEvent(@NonNull MotionEvent event)
      Pass the touch screen motion event down to the target view, or this view if it is the target.
      Parameters:
      event - The motion event to be dispatched.
      Returns:
      true if the event was handled by the view, false otherwise
    • onTouchEvent

      public boolean onTouchEvent(@NonNull MotionEvent event)
      Implement this method to handle touch screen motion events.

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

      Parameters:
      event - the touch event
      Returns:
      true if the event was handled by the view, false otherwise
    • handleScrollBarDragging

      @Internal protected boolean handleScrollBarDragging(MotionEvent event)
      Handles scroll bar dragging by mouse input.
      Parameters:
      event - The motion event.
      Returns:
      true if the event was handled as a scroll bar dragging, false otherwise.
    • isInScrollingContainer

      @Internal public boolean isInScrollingContainer()
    • cancelLongPress

      public void cancelLongPress()
      Cancels a pending long press. Your subclass can use this if you want the context menu to come up if the user presses and holds at the same place, but you don't want it to come up if they press and then move around enough to cause scrolling.
    • performClick

      public boolean performClick()
      Call this view's OnClickListener, if it is defined. Performs all normal actions associated with clicking: reporting accessibility event, playing a sound, etc.
      Returns:
      True there was an assigned OnClickListener that was called, false otherwise is returned.
    • callOnClick

      public boolean callOnClick()
      Directly call any attached OnClickListener. Unlike performClick(), this only calls the listener, and does not do any associated clicking actions like reporting an accessibility event.
      Returns:
      True there was an assigned OnClickListener that was called, false otherwise is returned.
    • performLongClick

      public boolean performLongClick()
      Calls this view's OnLongClickListener, if it is defined. Invokes the context menu if the OnLongClickListener did not consume the event.
      Returns:
      true if one of the above receivers consumed the event, false otherwise
    • performLongClick

      public boolean performLongClick(float x, float y)
      Calls this view's OnLongClickListener, if it is defined. Invokes the context menu if the OnLongClickListener did not consume the event, anchoring it to an (x,y) coordinate.
      Parameters:
      x - x coordinate of the anchoring touch event, or Float.NaN to disable anchoring
      y - y coordinate of the anchoring touch event, or Float.NaN to disable anchoring
      Returns:
      true if one of the above receivers consumed the event, false otherwise
    • performContextClick

      public boolean performContextClick(float x, float y)
      Call this view's OnContextClickListener, if it is defined.
      Parameters:
      x - the x coordinate of the context click
      y - the y coordinate of the context click
      Returns:
      True if there was an assigned OnContextClickListener that consumed the event, false otherwise.
    • performContextClick

      public boolean performContextClick()
      Call this view's OnContextClickListener, if it is defined.
      Returns:
      True if there was an assigned OnContextClickListener that consumed the event, false otherwise.
    • performButtonActionOnTouchDown

      @Internal protected boolean performButtonActionOnTouchDown(@NonNull MotionEvent event)
      Performs button-related actions during a touch down event.
      Parameters:
      event - The event.
      Returns:
      True if the down was consumed.
    • showContextMenu

      public final boolean showContextMenu()
      Shows the context menu for this view.
      Returns:
      true if the context menu was shown, false otherwise
      See Also:
    • showContextMenu

      public boolean showContextMenu(float x, float y)
      Shows the context menu for this view anchored to the specified view-relative coordinate.
      Parameters:
      x - the X coordinate in pixels relative to the view to which the menu should be anchored, or Float.NaN to disable anchoring
      y - the Y coordinate in pixels relative to the view to which the menu should be anchored, or Float.NaN to disable anchoring
      Returns:
      true if the context menu was shown, false otherwise
    • startActionMode

      public final ActionMode startActionMode(ActionMode.Callback callback)
      Start an action mode with the default type ActionMode.TYPE_PRIMARY.
      Parameters:
      callback - Callback that will control the lifecycle of the action mode
      Returns:
      The new action mode if it is started, null otherwise
      See Also:
    • startActionMode

      public ActionMode startActionMode(ActionMode.Callback callback, int type)
      Start an action mode with the given type.
      Parameters:
      callback - Callback that will control the lifecycle of the action mode
      type - One of ActionMode.TYPE_PRIMARY or ActionMode.TYPE_FLOATING.
      Returns:
      The new action mode if it is started, null otherwise
      See Also:
    • createContextMenu

      public final void createContextMenu(@NonNull ContextMenu menu)
      Show the context menu for this view. It is not safe to hold on to the menu after returning from this method.

      You should normally not overload this method. Overload onCreateContextMenu(ContextMenu) or define an View.OnCreateContextMenuListener to add items to the context menu.

      Parameters:
      menu - The context menu to populate
    • getContextMenuInfo

      protected ContextMenu.ContextMenuInfo getContextMenuInfo()
      Views should implement this if they have extra information to associate with the context menu. The return result is supplied as a parameter to the View.OnCreateContextMenuListener.onCreateContextMenu(ContextMenu, View, ContextMenuInfo) callback.
      Returns:
      Extra information about the item for which the context menu should be shown. This information will vary across different subclasses of View.
    • onCreateContextMenu

      protected void onCreateContextMenu(@NonNull ContextMenu menu)
      Views should implement this if the view itself is going to add items to the context menu.
      Parameters:
      menu - the context menu to populate
    • isTemporarilyDetached

      public final boolean isTemporarilyDetached()
      Tells whether the View is in the state between onStartTemporaryDetach() and onFinishTemporaryDetach().

      This method always returns true when called directly or indirectly from onStartTemporaryDetach(). The return value when called directly or indirectly from onFinishTemporaryDetach().

      Returns:
      true when the View is in the state between onStartTemporaryDetach() and onFinishTemporaryDetach().
    • dispatchStartTemporaryDetach

      @CallSuper public void dispatchStartTemporaryDetach()
      Dispatch onStartTemporaryDetach() to this View and its direct children if this is a container View.
    • onStartTemporaryDetach

      public void onStartTemporaryDetach()
      This is called when a container is going to temporarily detach a child, with ViewGroup.detachViewFromParent(View). It will either be followed by onFinishTemporaryDetach() or onDetachedFromWindow() when the container is done.
    • dispatchFinishTemporaryDetach

      @CallSuper public void dispatchFinishTemporaryDetach()
      Dispatch onFinishTemporaryDetach() to this View and its direct children if this is a container View.
    • onFinishTemporaryDetach

      public void onFinishTemporaryDetach()
      Called after onStartTemporaryDetach() when the container is done changing the view.
    • getKeyDispatcherState

      @Nullable public final KeyEvent.DispatcherState getKeyDispatcherState()
      Return the global KeyEvent.DispatcherState for this view's window. Returns null if the view is not currently attached to the window. Normally you will not need to use this directly, but just use the standard high-level event callbacks like onKeyDown(int, KeyEvent).
    • dispatchKeyEvent

      public boolean dispatchKeyEvent(@NonNull KeyEvent event)
      Dispatch a key event to the next view on the focus path. This path runs from the top of the view tree down to the currently focused view. If this view has focus, it will dispatch to itself. Otherwise it will dispatch the next node down the focus path. This method also fires any key listeners.
      Parameters:
      event - The key event to be dispatched.
      Returns:
      True if the event was handled, false otherwise.
    • dispatchKeyShortcutEvent

      public boolean dispatchKeyShortcutEvent(@NonNull KeyEvent event)
      Dispatches a key shortcut event.
      Parameters:
      event - The key event to be dispatched.
      Returns:
      True if the event was handled by the view, false otherwise.
    • onKeyDown

      public boolean onKeyDown(int keyCode, @NonNull KeyEvent event)
      Default implementation: perform press of the view when KeyEvent.KEY_ENTER, KeyEvent.KEY_KP_ENTER or KeyEvent.KEY_SPACE is released, if the view is enabled and clickable.
      Parameters:
      keyCode - a key code that represents the button pressed, from KeyEvent
      event - the KeyEvent object that defines the button action
    • onKeyUp

      public boolean onKeyUp(int keyCode, @NonNull KeyEvent event)
      Default implementation: perform clicking of the view when KeyEvent.KEY_ENTER, KeyEvent.KEY_KP_ENTER or KeyEvent.KEY_SPACE is released.
      Parameters:
      keyCode - A key code that represents the button pressed, from KeyEvent.
      event - The KeyEvent object that defines the button action.
    • onKeyShortcut

      public boolean onKeyShortcut(int keyCode, @NonNull KeyEvent event)
      Called on the focused view when a key shortcut event is not handled. Override this method to implement local key shortcuts for the View. Key shortcuts can also be implemented by setting the shortcut property of menu items.
      Parameters:
      keyCode - The value in event.getKeyCode().
      event - Description of the key event.
      Returns:
      If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.
    • getHitRect

      public void getHitRect(Rect outRect)
      Hit rectangle in parent's coordinates
      Parameters:
      outRect - The hit rectangle of the view.
    • pointInView

      @Internal public boolean pointInView(float localX, float localY, float slop)
      Utility method to determine whether the given point, in local coordinates, is inside the view, where the area of the view is expanded by the slop factor. This method is called while processing touch-move events to determine if the event is still within the view.
    • getFocusedRect

      public void getFocusedRect(@NonNull Rect r)
      When a view has focus and the user navigates away from it, the next view is searched for starting from the rectangle filled in by this method.

      By default, the rectangle is the getDrawingRect(Rect)) of the view. However, if your view maintains some idea of internal selection, such as a cursor, or a selected row or column, you should override this method and fill in a more specific rectangle.

      Parameters:
      r - The rectangle to fill in, in this view's coordinates.
    • getGlobalVisibleRect

      public boolean getGlobalVisibleRect(@NonNull Rect r, @Nullable Point globalOffset)
      If some part of this view is not clipped by any of its parents, then return that area in r in global (root) coordinates. To convert r to local coordinates (without taking possible View rotations into account), offset it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). If the view is completely clipped or translated out, return false.
      Parameters:
      r - If true is returned, r holds the global coordinates of the visible portion of this view.
      globalOffset - If true is returned, globalOffset holds the dx,dy between this view and its root. globalOffset may be null.
      Returns:
      true if r is non-empty (i.e. part of the view is visible at the root level.
    • getGlobalVisibleRect

      public final boolean getGlobalVisibleRect(@NonNull Rect r)
    • getLocalVisibleRect

      public final boolean getLocalVisibleRect(@NonNull Rect r)
    • offsetTopAndBottom

      public void offsetTopAndBottom(int offset)
      Offset this view's vertical location by the specified number of pixels.
      Parameters:
      offset - the number of pixels to offset the view by
    • offsetLeftAndRight

      public void offsetLeftAndRight(int offset)
      Offset this view's horizontal location by the specified amount of pixels.
      Parameters:
      offset - the number of pixels to offset the view by
    • getContext

      public final Context getContext()
      Returns the context the view is running in, through which it can access the current theme, resources, etc.
      Returns:
      The view's Context.
    • isInTouchMode

      public boolean isInTouchMode()
      Returns whether the device is currently in touch mode. Touch mode is entered once the user begins interacting with the device by touch, and affects various things like whether focus is always visible to the user.
      Returns:
      Whether the device is in touch mode.
    • onResolvePointerIcon

      public PointerIcon onResolvePointerIcon(@NonNull MotionEvent event)
      Returns the pointer icon for the motion event, or null if it doesn't specify the icon. The default implementation does not care the location or event types, but some subclasses may use it (such as WebViews).
      Parameters:
      event - The MotionEvent from a mouse
      See Also:
    • setTooltipText

      public void setTooltipText(@Nullable CharSequence tooltipText)
      Sets the tooltip text which will be displayed in a small popup next to the view.

      The tooltip will be displayed:

      • On long click, unless it is handled otherwise (by OnLongClickListener or a context menu).
      • On hover, after a brief delay since the pointer has stopped moving

      Note: Do not override this method, as it will have no effect on the text displayed in the tooltip.

      Parameters:
      tooltipText - the tooltip text, or null if no tooltip is required
      See Also:
    • getTooltipText

      @Nullable public CharSequence getTooltipText()
      Returns the view's tooltip text. Note: Do not override this method, as it will have no effect on the text displayed in the tooltip. You must call setTooltipText(CharSequence) to modify the tooltip text.
      Returns:
      the tooltip text
      See Also:
    • getTooltipView

      @Internal public View getTooltipView()
      Returns:
      The content view of the tooltip popup currently being shown, or null if the tooltip is not showing.
    • setTransitionVisibility

      public final void setTransitionVisibility(int visibility)
      Changes the visibility of this View without triggering any other changes. This should only be used by animation frameworks, such as Transition, where visibility changes should not adjust focus or trigger a new layout. Application developers should use setVisibility(int) instead to ensure that the hierarchy is correctly updated.

      Only call this method when a temporary visibility must be applied during an animation and the original visibility value is guaranteed to be reset after the animation completes. Use setVisibility(int) in all other cases.

      Parameters:
      visibility - One of VISIBLE, INVISIBLE, or GONE.
      See Also:
    • setTransitionName

      public final void setTransitionName(String transitionName)
      Sets the name of the View to be used to identify Views in Transitions. Names should be unique in the View hierarchy.
      Parameters:
      transitionName - The name of the View to uniquely identify it for Transitions.
    • getTransitionName

      public String getTransitionName()
      Returns the name of the View to be used to identify Views in Transitions. Names should be unique in the View hierarchy.

      This returns null if the View has not been given a name.

      Returns:
      The name used of the View to be used to identify Views in Transitions or null if no name has been given.
    • toString

      public String toString()
      Overrides:
      toString in class Object