Class View
- All Implemented Interfaces:
Drawable.Callback
- Direct Known Subclasses:
ImageView
,LinearPagerIndicator
,ProgressBar
,TextView
,ViewGroup
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:
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic class
Creates an image that the system displays during the drag and drop operation.static @interface
static @interface
static @interface
static @interface
static @interface
static @interface
static interface
Interface definition for a callback to be invoked when this view is attached or detached from its window.static interface
Interface definition for a callback to be invoked when a view is clicked.static interface
Interface definition for a callback to be invoked when a view is context clicked.static interface
Interface definition for a callback to be invoked when the context menu for this view is being built.static interface
Interface definition for a callback to be invoked when a drag is being dispatched to this view.static interface
Interface definition for a callback to be invoked when the focus state of a view changed.static interface
Interface definition for a callback to be invoked when a generic motion event is dispatched to this view.static interface
Interface definition for a callback to be invoked when a hover event is dispatched to this view.static interface
Interface definition for a callback to be invoked when a hardware key event is dispatched to this view.static interface
Interface definition for a callback to be invoked when the layout bounds of a view changes due to layout processing.static interface
Interface definition for a callback to be invoked when a view has been clicked and held.static interface
Interface definition for a callback to be invoked when the scroll X or Y positions of a view change.static interface
Interface definition for a callback to be invoked when a touch event is dispatched to this view.static @interface
static @interface
static @interface
static @interface
static @interface
static @interface
-
Field Summary
Modifier and TypeFieldDescriptionstatic final FloatProperty
<View> A Property wrapper around thealpha
functionality handled by thesetAlpha(float)
andgetAlpha()
methods.static final IntProperty
<View> A Property wrapper around thebottom
functionality handled by thesetBottom(int)
andgetBottom()
methods.protected static final int[]
Indicates the view has no states set.protected static final int[]
Indicates the view is enabled, focused and selected.protected static final int[]
Indicates the view is enabled, focused, selected and its window has the focus.protected static final int[]
Indicates the view is enabled and has the focus.protected static final int[]
Indicates the view is enabled, focused and its window has the focus.protected static final int[]
Indicates the view is enabled and selected.protected static final int[]
Indicates the view is enabled, selected and its window has the focus.protected static final int[]
Indicates the view is enabled.protected static final int[]
Indicates the view is enabled and that its window has focus.static final int
Use withfocusSearch(int)
.static final int
Use withfocusSearch(int)
.static final int
Use withfocusSearch(int)
.static final int
Use withfocusSearch(int)
.static final int
Use withfocusSearch(int)
.static final int
Use withfocusSearch(int)
.static final int
This view wants keystrokes.static final int
This view determines focusability automatically.static final int
View flag indicating whetheraddFocusables(ArrayList, int, int)
should add all focusable Views regardless if they are focusable in touch mode.static final int
View flag indicating whetheraddFocusables(ArrayList, int, int)
should add only Views focusable in touch mode.protected static final int[]
Indicates the view is focused and selected.protected static final int[]
Indicates the view is focused, selected and its window has the focus.protected static final int[]
Indicates the view is focused.protected static final int[]
Indicates the view has the focus and that its window has the focus.static final int
This view is invisible, and it doesn't take any space for layout purposes.static final int
View flag indicating whether this view should have haptic feedback enabled for events such as long presses.static final int
This view is invisible, but it still takes up space for layout purposes.static final int
Horizontal layout direction of this view is inherited from its parent.static final int
Horizontal layout direction of this view is from deduced from the default language script for the locale.static final int
Horizontal layout direction of this view is from Left to Right.static final int
Horizontal layout direction of this view is from Right to Left.static final int
A flag to indicate that the layout direction of this view has not been defined yet.static final IntProperty
<View> static final int
Bit shift ofMEASURED_STATE_MASK
to get to the height bits for functions that combine both width and height into a single int, such asgetMeasuredState()
and the childState argument ofresolveSizeAndState(int, int, int)
.static final int
Bits ofgetMeasuredWidthAndState()
andgetMeasuredWidthAndState()
that provide the actual measured size.static final int
Bits ofgetMeasuredWidthAndState()
andgetMeasuredWidthAndState()
that provide the additional state bits.static final int
Bit ofgetMeasuredWidthAndState()
andgetMeasuredWidthAndState()
that indicates the measured size is smaller that the space the view would like to have.protected int
The final computed bottom padding in pixels that is used for drawing.protected int
The final computed left padding in pixels that is used for drawing.protected int
The final computed right padding in pixels that is used for drawing.protected int
The final computed top padding in pixels that is used for drawing.protected int
The offset, in pixels, by which the content of this view is scrolled horizontally.protected int
The offset, in pixels, by which the content of this view is scrolled vertically.static final int
Used to mark a View that has no ID.static final int
This view does not want keystrokes.static final int
Always allow a user to over-scroll this view, provided it is a view that can scroll.static final int
Allow a user to over-scroll this view only if the content is large enough to meaningfully scroll, provided it is a view that can scroll.static final int
Never allow a user to over-scroll this view.protected static final int[]
Indicates the view is pressed, enabled, focused and selected.protected static final int[]
Indicates the view is pressed, enabled, focused, selected and its window has the focus.protected static final int[]
Indicates the view is pressed, enabled and focused.protected static final int[]
Indicates the view is pressed, enabled, focused and its window has the focus.protected static final int[]
Indicates the view is pressed, enabled and selected.protected static final int[]
Indicates the view is pressed, enabled, selected and its window has the focus.protected static final int[]
Indicates the view is pressed and enabled.protected static final int[]
Indicates the view is pressed, enabled and its window has the focus.protected static final int[]
Indicates the view is pressed, focused and selected.protected static final int[]
Indicates the view is pressed, focused, selected and its window has the focus.protected static final int[]
Indicates the view is pressed and focused.protected static final int[]
Indicates the view is pressed, focused and its window has the focus.protected static final int[]
Indicates the view is pressed and selected.protected static final int[]
Indicates the view is pressed, selected and its window has the focus.protected static final int[]
Indicates the view is pressed.protected static final int[]
Indicates the view is pressed and its window has the focus.static final IntProperty
<View> A Property wrapper around theright
functionality handled by thesetRight(int)
andgetRight()
methods.static final FloatProperty
<View> A Property wrapper around therotation
functionality handled by thesetRotation(float)
andgetRotation()
methods.static final FloatProperty
<View> A Property wrapper around therotationX
functionality handled by thesetRotationX(float)
andgetRotationX()
methods.static final FloatProperty
<View> A Property wrapper around therotationY
functionality handled by thesetRotationY(float)
andgetRotationY()
methods.static final FloatProperty
<View> A Property wrapper around thescaleX
functionality handled by thesetScaleX(float)
andgetScaleX()
methods.static final FloatProperty
<View> A Property wrapper around thescaleY
functionality handled by thesetScaleY(float)
andgetScaleY()
methods.static final int
Indicates scrolling along the horizontal axis.static final int
Indicates no axis of view scrolling.static final int
Indicates scrolling along the vertical axis.static final int
Scroll indicator direction for the bottom edge of the view.static final int
Scroll indicator direction for the ending edge of the view.static final int
Scroll indicator direction for the left edge of the view.static final int
Scroll indicator direction for the right edge of the view.static final int
Scroll indicator direction for the starting edge of the view.static final int
Scroll indicator direction for the top edge of the view.static final IntProperty
<View> A Property wrapper around thescrollX
functionality handled by thesetScrollX(int)
andgetScrollX()
methods.static final IntProperty
<View> A Property wrapper around thescrollY
functionality handled by thesetScrollY(int)
andgetScrollY()
methods.static final int
The scrollbar style to display the scrollbars inside the padded area, increasing the padding of the view.static final int
The scrollbar style to display the scrollbars inside the content area, without increasing the padding.static final int
The scrollbar style to display the scrollbars at the edge of the view, increasing the padding of the view.static final int
The scrollbar style to display the scrollbars at the edge of the view, without increasing the padding.protected static final int[]
Indicates the view is selected.protected static final int[]
Indicates the view is selected and that its window has the focus.static final int
View flag indicating whether this view should have sound effects enabled for events such as clicking and touching.static final int
Center the paragraph, e.g.static final int
Default for the root view.static final int
Default text alignment.static final int
Align to the end of the paragraph, e.g.static final int
Align to the start of the paragraph, e.g.static final int
Align to the end of the view, which is ALIGN_RIGHT if the view's resolved layoutDirection is LTR, and ALIGN_LEFT otherwise.static final int
Align to the start of the view, which is ALIGN_LEFT if the view's resolved layoutDirection is LTR, and ALIGN_RIGHT otherwise.static final int
Text direction is using "any-RTL" algorithm.static final int
Text direction is using "first strong algorithm".static final int
Text direction is using "first strong algorithm".static final int
Text direction is using "first strong algorithm".static final int
Text direction is inherited throughViewGroup
static final int
Text direction is coming from the system Locale.static final int
Text direction is forced to LTR.static final int
Text direction is forced to RTL.static final IntProperty
<View> static final FloatProperty
<View> A Property wrapper around thetranslationX
functionality handled by thesetTranslationX(float)
andgetTranslationX()
methods.static final FloatProperty
<View> A Property wrapper around thetranslationY
functionality handled by thesetTranslationY(float)
andgetTranslationY()
methods.static final FloatProperty
<View> A Property wrapper around thetranslationZ
functionality handled by thesetTranslationZ(float)
andgetTranslationZ()
methods.static final int
Indicates that the input type for the gesture is caused by something which is not a user touching a screen.static final int
Indicates that the input type for the gesture is from a user touching the screen.protected static final org.apache.logging.log4j.Marker
The logging marker used by this class withLogger
.static final int
This view is visible.protected static final int[]
Indicates the view's window has focus.static final FloatProperty
<View> static final FloatProperty
<View> static final FloatProperty
<View> -
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionfinal 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.void
addFocusables
(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.void
addKeyboardNavigationClusters
(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.void
Add a listener for attach state changes.void
Add a listener that will be called when the bounds of the view change due to layout processing.void
addTouchables
(ArrayList<View> views) Add any touchable views that are descendants of this view (possibly including this view if it is touchable itself) to views.protected final boolean
Trigger the scrollbars to draw.protected boolean
awakenScrollBars
(int startDelay) Trigger the scrollbars to draw.boolean
Directly call any attached OnClickListener.void
Cancels a pending long press.final void
Cancel any deferred high-level input events that were previously posted to the event queue.protected boolean
Returns whether this view can receive pointer events.final boolean
Check if layout direction resolution can be done.final boolean
Check if text alignment resolution can be done.final boolean
Check if text direction resolution can be done.boolean
canScrollHorizontally
(int direction) Check if this view can be scrolled horizontally in a certain direction.boolean
canScrollVertically
(int direction) Check if this view can be scrolled vertically in a certain direction.void
Called when this view wants to give up focus.static int
combineMeasuredStates
(int curState, int newState) Merge two states as returned bygetMeasuredState()
.protected int
Compute the horizontal extent of the horizontal scrollbar's thumb within the horizontal range.protected int
Compute the horizontal offset of the horizontal scrollbar's thumb within the horizontal range.protected int
Compute the horizontal range that the horizontal scrollbar represents.void
Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary.protected int
Compute the vertical extent of the vertical scrollbar's thumb within the vertical range.protected int
Compute the vertical offset of the vertical scrollbar's thumb within the horizontal range.protected int
Compute the vertical range that the vertical scrollbar represents.final void
createContextMenu
(ContextMenu menu) Show the context menu for this view.protected void
dispatchDraw
(Canvas canvas) Draw the child views.void
dispatchDrawableHotspotChanged
(float x, float y) Dispatches drawableHotspotChanged to all of this View's children.void
DispatchonFinishTemporaryDetach()
to this View and its direct children if this is a container View.boolean
Dispatch a generic motion event.protected boolean
Dispatch a generic motion event to the view under the first pointer.protected boolean
dispatchHoverEvent
(MotionEvent event) Dispatch a hover event.boolean
dispatchKeyEvent
(KeyEvent event) Dispatch a key event to the next view on the focus path.boolean
dispatchKeyShortcutEvent
(KeyEvent event) Dispatches a key shortcut event.boolean
dispatchNestedFling
(float velocityX, float velocityY, boolean consumed) Dispatch a fling to a nested scrolling parent.boolean
dispatchNestedPreFling
(float velocityX, float velocityY) Dispatch a fling to a nested scrolling parent before it is processed by this view.boolean
dispatchNestedPreScroll
(int dx, int dy, int[] consumed, int[] offsetInWindow, int type) Dispatch one step of a nested scroll in progress before this view consumes any portion of it.boolean
dispatchNestedScroll
(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow, int type, int[] consumed) Dispatch one step of a nested scroll in progress.final boolean
dispatchPointerEvent
(MotionEvent event) Dispatch a pointer event.protected void
dispatchSetActivated
(boolean activated) Dispatch setActivated to all of this View's children.protected void
dispatchSetPressed
(boolean pressed) Dispatch setPressed to all of this View's children.protected void
dispatchSetSelected
(boolean selected) Dispatch setSelected to all of this View's children.void
DispatchonStartTemporaryDetach()
to this View and its direct children if this is a container View.boolean
dispatchTouchEvent
(MotionEvent event) Pass the touch screen motion event down to the target view, or this view if it is the target.protected void
dispatchVisibilityChanged
(View changedView, int visibility) Dispatch a view visibility change down the view hierarchy.void
dispatchWindowFocusChanged
(boolean hasFocus) Called when the window containing this view gains or loses window focus.void
dispatchWindowVisibilityChanged
(int visibility) Dispatch a window visibility change down the view hierarchy.final int
dp
(float value) Utility to get the size in pixels that matches the view layout standards.void
Base method that directly draws this view and its background, foreground, overlay and all children to the given canvas.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.protected void
This function is called whenever the state of the view changes in such a way that it impacts the state of drawables being shown.Find the view in the hierarchy rooted at this view that currently has focus.final <T extends View>
TfindViewById
(int id) Finds the first descendant view with the given ID, the view itself if the ID matchesgetId()
, ornull
if the ID is invalid (< 0) or there is no matching view in the hierarchy.final <T extends View>
TfindViewByPredicate
(Predicate<View> predicate) Look for a child view that matches the specified predicate.final <T extends View>
TfindViewByPredicateInsideOut
(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.protected <T extends View>
TfindViewByPredicateTraversal
(Predicate<View> predicate, View childToSkip) protected <T extends View>
TfindViewTraversal
(int id) focusSearch
(int direction) Find the nearest view in the specified direction that can take focus.void
forceHasOverlappingRendering
(boolean hasOverlappingRendering) Sets the behavior for overlapping rendering for this view (seehasOverlappingRendering()
for more details on this behavior).void
Forces this view to be laid out during the next layout pass.static int
Generate a value suitable for use insetId(int)
.float
getAlpha()
The opacity of the view.final Matrix
Changes the transition matrix on the view.Gets the background drawableint
Return the offset of the widget's text baseline from the widget's top boundary.final int
Bottom position of this view relative to its parent.void
getBoundsOnScreen
(Rect outRect) Gets the location of this view in screen coordinates.void
getBoundsOnScreen
(Rect outRect, boolean clipToParent) Gets the location of this view in screen coordinates.final Context
Returns the context the view is running in, through which it can access the current theme, resources, etc.protected ContextMenu.ContextMenuInfo
Views should implement this if they have extra information to associate with the context menu.static int
getDefaultSize
(int size, int measureSpec) Utility to return a default size.final int[]
Return an array of resource IDs of the drawable states representing the current state of the view.void
getDrawingRect
(Rect outRect) Return the visible drawing bounds of your view.float
The base elevation of this view relative to its parent, in pixels.int
Get the fading edge flags, used for inspection.int
Get the fading edge length, used for inspectionint
Returns the focusable setting for this 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.void
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.Returns the drawable used as the foreground of this View.int
Describes how the foreground is positioned.final boolean
boolean
getGlobalVisibleRect
(Rect r, 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.final Handler
final boolean
Returns the value for overlapping rendering that is used internally.final int
Get the height of the view.void
getHitRect
(Rect outRect) Hit rectangle in parent's coordinatesprotected int
Returns the height of the horizontal scrollbar.Returns the currently configured Drawable for the thumb of the horizontal scroll bar if it exists, null otherwise.Returns the currently configured Drawable for the track of the horizontal scroll bar if it exists, null otherwise.int
getId()
Returns this view's identifier.final Matrix
Utility method to retrieve the inverse of the current matrix property.final KeyEvent.DispatcherState
Return the globalKeyEvent.DispatcherState
for this view's window.final int
Returns the resolved layout direction for this view.Get the LayoutParams associated with this view.final int
getLeft()
Left position of this view relative to its parent.final boolean
void
getLocationInWindow
(int[] outLocation) Computes the coordinates of this view in its window.void
getLocationOnScreen
(int[] outLocation) Computes the coordinates of this view on the screen.final Matrix
The transform matrix of this view, which is calculated based on the current rotation, scale, and pivot properties.final int
LikegetMeasuredHeightAndState()
, but only returns the raw height component (that is the result is masked byMEASURED_SIZE_MASK
).final int
Return the full height measurement information for this view as computed by the most recent call tomeasure(int, int)
.final int
Return only the state bits ofgetMeasuredWidthAndState()
andgetMeasuredHeightAndState()
, combined into one integer.final int
LikegetMeasuredWidthAndState()
, but only returns the raw width component (that is the result is masked byMEASURED_SIZE_MASK
).final int
Return the full width measurement information for this view as computed by the most recent call tomeasure(int, int)
.int
Returns the minimum height of the view.int
Returns the minimum width of the view.int
Gets the id of the root of the next keyboard navigation cluster.int
Gets the id of the view to use when the next focus isFOCUS_DOWN
.int
Gets the id of the view to use when the next focus isFOCUS_FORWARD
.int
Gets the id of the view to use when the next focus isFOCUS_LEFT
.int
Gets the id of the view to use when the next focus isFOCUS_RIGHT
.int
Gets the id of the view to use when the next focus isFOCUS_UP
.Returns the focus-change callback registered for this view.int
Returns the over-scroll mode for this view.int
Returns the bottom padding of this view.int
Returns the end padding of this view depending on its resolved layout direction.int
Returns the left padding of this view.int
Returns the right padding of this view.int
Returns the start padding of this view depending on its resolved layout direction.int
Returns the top padding of this view.final ViewParent
Gets the parent of this view.float
float
final int
Returns the layout direction for this view.final int
Return the value specifying the text alignment or policy that was set withsetTextAlignment(int)
.final int
Return the value specifying the text direction or policy that was set withsetTextDirection(int)
.final boolean
Returns this view's preference for reveal behavior when it gains focus.final int
getRight()
Right position of this view relative to its parent.final View
Finds the topmost view in the current view hierarchy.float
The degrees that the view is rotated around the pivot point.float
The degrees that the view is rotated around the horizontal axis through the pivot point.float
The degrees that the view is rotated around the vertical axis through the pivot point.float
The amount that the view is scaled in x around the pivot point, as a proportion of the view's unscaled width.float
The amount that the view is scaled in y around the pivot point, as a proportion of the view's unscaled height.int
Returns the delay before scrollbars fade.int
Returns the scrollbar fade duration.int
Returns the scrollbar size.int
Returns the current scrollbar style.int
Returns a bitmask representing the enabled scroll indicators.final int
Return the scrolled left position of this view.final int
Return the scrolled top position of this view.Returns the current StateListAnimator if exists.protected int
Returns the suggested minimum height that the view should use.protected int
Returns the suggested minimum width that the view should use.getTag
(int key) Returns the tag associated with this view and the specified key.final int
Return the resolved text alignment.final int
Return the resolved text direction.Returns the view's tooltip text.final int
getTop()
Top position of this view relative to its parent.Find and return all touchable views that are descendants of this view, possibly including this view if it is touchable itself.final float
This property is intended only for use by theFade
transition, which animates it to produce a visual translucency that does not side effect (or get affected by) the real alpha property.Returns the name of the View to be used to identify Views in Transitions.float
The horizontal location of this view relative to itsleft
position.float
The vertical location of this view relative to itstop
position.float
The depth location of this view relative to itselevation
.int
Returns the size of the vertical faded edges used to indicate that more content in this view is visible.Returns the currently configured Drawable for the thumb of the vertical scroll bar if it exists, null otherwise.Returns the currently configured Drawable for the track of the vertical scroll bar if it exists, null otherwise.int
Returns the width of the vertical scrollbar.final ViewRoot
Gets the view root associated with the View.final ViewTreeObserver
Returns the ViewTreeObserver for this view's hierarchy.int
Returns the visibility status for this view.final int
getWidth()
Get the width of the view.protected int
final int
float
getX()
The visual x position of this view, in pixels.float
getY()
The visual y position of this view, in pixels.float
getZ()
The visual z position of this view, in pixels.protected boolean
Handles scroll bar dragging by mouse input.final boolean
Returns true if this view is focusable or if it contains a reachable View for which this method returnstrue
.boolean
hasFocus()
Returns true if this view has focus itself, or is the ancestor of the view that has focus.final boolean
Returns true if this view is focusable or if it contains a reachable View for which this method returnstrue
.final boolean
Returns true if the transform matrix is the identity matrix.boolean
hasNestedScrollingParent
(int type) Returns true if this view has a nested scrolling parent for the given input type.boolean
Return whether this view has an attached OnClickListener.boolean
Return whether this view has an attached OnLongClickListener.boolean
Returns whether this View has content which overlaps.boolean
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.boolean
boolean
Returns true if this view is in a window that currently has window focus.protected void
internalSetPadding
(int left, int top, int right, int bottom) final void
Invalidate the whole view.void
invalidateDrawable
(Drawable drawable) Invalidates the specified Drawable.boolean
Indicates the activation state of this view.boolean
Returns true if this view is currently attached to a window.boolean
Indicates whether this view reacts to click events or not.boolean
Indicates whether this view reacts to context clicks or not.boolean
Indicates whether this duplicates its drawable state from its parent.boolean
Returns the enabled status for this view.final boolean
Returns whether this View is currently able to take focus.final boolean
When a view is focusable, it may not want to take focus when in touch mode.boolean
Returns true if this view has focusfinal boolean
Returns whether this View should receive focus when the focus is restored for the view hierarchy containing this view.boolean
Magic bit used to support features of framework-internal window decor implementation details.boolean
boolean
Indicate whether the horizontal edges are faded when the view is scrolled horizontally.boolean
Indicate whether the horizontal scrollbar should have or not.boolean
Returns true if the view is currently hovered.final boolean
Returns whether the view hierarchy is currently undergoing a layout pass.boolean
boolean
Returns whether the device is currently in touch mode.final boolean
Returns whether this View is a root of a keyboard navigation cluster.boolean
Returns true if this view has been through at least one layout since it was last attached to or detached from a window.final boolean
final boolean
boolean
Indicates whether or not this view's layout will be requested during the next hierarchy layout pass.final boolean
Indicates whether this view's layout is right-to-left.boolean
Indicates whether this view reacts to long click events or not.boolean
Returns true if nested scrolling is enabled for this view.boolean
Return if the padding has been set through relative valuessetPaddingRelative(int, int, int, int)
or throughboolean
Returns whether a pivot has been set by a call tosetPivotX(float)
orsetPivotY(float)
.boolean
Indicates whether the view is currently in pressed state.boolean
boolean
Returns true if scrollbars will fade when this view is not scrollingboolean
Indicates the selection state of this view.final boolean
Returnstrue
when the View is attached and the system developer setting to show the layout bounds is enabled orfalse
otherwise.boolean
isShown()
Returns the visibility of this view and all of its ancestorsboolean
final boolean
Tells whether theView
is in the state betweenonStartTemporaryDetach()
andonFinishTemporaryDetach()
.final boolean
final boolean
final boolean
final boolean
boolean
Indicate whether the vertical edges are faded when the view is scrolled horizontally.boolean
Indicate whether the vertical scrollbar should have or not.protected boolean
Override this if the vertical scrollbar needs to be hidden in a subclass, like when FastScroller is visible.void
CallDrawable.jumpToCurrentState()
on all Drawable objects associated with this view.keyboardNavigationClusterSearch
(View currentCluster, int direction) Find the nearest keyboard navigation cluster in the specified direction.void
layout
(int l, int t, int r, int b) Specifies the rectangle area of this view and all its descendants.void
mapRectFromViewToScreenCoords
(RectF rect, boolean clipToParent) Map a rectangle from view-relative coordinates to screen-relative coordinatesfinal void
measure
(int widthMeasureSpec, int heightMeasureSpec) This is called to find out how big a view should be.protected static int[]
mergeDrawableStates
(int[] baseState, int[] additionalState) Merge your own state values in additionalState into the base state values baseState that were returned byonCreateDrawableState(int)
.void
offsetLeftAndRight
(int offset) Offset this view's horizontal location by the specified amount of pixels.void
offsetTopAndBottom
(int offset) Offset this view's vertical location by the specified number of pixels.protected void
This is called when the view is attached to a window.void
Called as the result of a call tocancelPendingInputEvents()
on this view or a parent view.protected void
Views should implement this if the view itself is going to add items to the context menu.protected int[]
onCreateDrawableState
(int extraSpace) Generate the newDrawable
state for this view.protected void
This is called when the view is detached from a window.boolean
onDragEvent
(DragEvent event) Handle primitive drag event of this viewprotected void
Draw the content of this view, implement this to do your drawing.void
onDrawForeground
(Canvas canvas) Draw any foreground content for this view.protected final void
onDrawScrollBars
(Canvas canvas) Request the drawing of the horizontal and the vertical scrollbar.void
Called afteronStartTemporaryDetach()
when the container is done changing the view.protected void
onFocusChanged
(boolean gainFocus, int direction, Rect previouslyFocusedRect) Called by the view system when the focus state of this view changes.boolean
onGenericMotionEvent
(MotionEvent event) Implement this method to handle generic motion events.void
onHoverChanged
(boolean hovered) Implement this method to handle hover state changes.boolean
onHoverEvent
(MotionEvent event) Implement this method to handle hover events.boolean
Default implementation: perform press of the view whenKeyEvent.KEY_ENTER
,KeyEvent.KEY_KP_ENTER
orKeyEvent.KEY_SPACE
is released, if the view is enabled and clickable.boolean
onKeyShortcut
(int keyCode, KeyEvent event) Called on the focused view when a key shortcut event is not handled.boolean
Default implementation: perform clicking of the view whenKeyEvent.KEY_ENTER
,KeyEvent.KEY_KP_ENTER
orKeyEvent.KEY_SPACE
is released.protected void
onLayout
(boolean changed, int left, int top, int right, int bottom) Called fromlayout(int, int, int, int)
when this view should assign a size and position to each of its children.protected void
onMeasure
(int widthMeasureSpec, int heightMeasureSpec) Measure the view and its content to determine the measured width and the measured height.protected void
onOverScrolled
(int scrollX, int scrollY, boolean clampedX, boolean clampedY) Called byoverScrollBy(int, int, int, int, int, int, int, int, boolean)
to respond to the results of an over-scroll operation.void
onResolveDrawables
(int layoutDirection) Called when layout direction has been resolved.onResolvePointerIcon
(MotionEvent event) Returns the pointer icon for the motion event, or null if it doesn't specify the icon.protected void
onRtlPropertiesChanged
(int layoutDirection) Called when any RTL property (layout direction or text direction or text alignment) has been changed.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).protected void
onSizeChanged
(int width, int height, int prevWidth, int prevHeight) Called when width or height changedvoid
This is called when a container is going to temporarily detach a child, withViewGroup.detachViewFromParent(View)
.boolean
onTouchEvent
(MotionEvent event) Implement this method to handle touch screen motion events.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.protected void
onVisibilityChanged
(View changedView, int visibility) Called when the visibility of the view or an ancestor of the view has changed.void
onWindowFocusChanged
(boolean hasWindowFocus) Called when the window containing this view gains or loses focus.protected void
onWindowVisibilityChanged
(int visibility) 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.protected boolean
Performs button-related actions during a touch down event.boolean
Call this view's OnClickListener, if it is defined.boolean
Call this view's OnContextClickListener, if it is defined.boolean
performContextClick
(float x, float y) Call this view's OnContextClickListener, if it is defined.final boolean
performHapticFeedback
(int feedbackConstant) BZZZTT!!1!boolean
performHapticFeedback
(int feedbackConstant, int flags) BZZZTT!!1!boolean
Calls this view's OnLongClickListener, if it is defined.boolean
performLongClick
(float x, float y) Calls this view's OnLongClickListener, if it is defined.void
playSoundEffect
(int soundConstant) Play a sound effect for this view.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.final boolean
Causes the Runnable to be added to the task queue.final boolean
postDelayed
(Runnable action, long delayMillis) Causes the Runnable to be added to the task queue, to be run after the specified amount of time elapses.final void
Cause an invalidate to happen on a subsequent cycle through the event loop.final void
postInvalidateDelayed
(long delayMilliseconds) Cause an invalidate to happen on a subsequent cycle through the event loop.final void
Cause an invalidate to happen on the next animation time step, typically the next display frame.final void
postOnAnimation
(Runnable action) Causes the runnable to execute on the next animation time step.final void
postOnAnimationDelayed
(Runnable action, long delayMillis) Causes the Runnable to execute on the next animation time step, after the specified amount of time elapses.void
Call this to force a view to update its drawable state.final void
removeCallbacks
(Runnable action) Removes the specified Runnable from the message queue.void
Remove a listener for attach state changes.void
Remove a listener for layout changes.final boolean
Call this to try to give focus to a specific view or to one of its descendants.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.boolean
requestFocus
(int direction, 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.void
Call this when something has changed which has invalidated the layout of this view.boolean
requestRectangleOnScreen
(Rect rectangle) Request that a rectangle of this view be visible on the screen, scrolling if necessary just enough.boolean
requestRectangleOnScreen
(Rect rectangle, boolean immediate) Request that a rectangle of this view be visible on the screen, scrolling if necessary just enough.final <T extends View>
TrequireViewById
(int id) Finds the first descendant view with the given ID, the view itself if the ID matchesgetId()
, or results in an error.void
Clears any pivot previously set by a call tosetPivotX(float)
orsetPivotY(float)
.protected void
protected void
Resolve the Drawables depending on the layout direction.boolean
Resolve and cache the layout direction.void
Resolve the layout parameters depending on the resolved layout directionvoid
Resolves padding depending on layout direction, if applicable, and recomputes internal padding values to adjust for scroll bars.boolean
Resolve all RTL related properties.static int
resolveSize
(int size, int measureSpec) Version ofresolveSizeAndState(int, int, int)
returning only theMEASURED_SIZE_MASK
bits of the result.static int
resolveSizeAndState
(int size, int measureSpec, int childMeasuredState) Utility to reconcile a desired size and state, with constraints imposed by a MeasureSpec.boolean
Resolve the text alignment.boolean
Resolve the text direction.boolean
Gives focus to the default-focus view in the view hierarchy that has this view as a root.final void
scheduleDrawable
(Drawable who, Runnable what, long when) Schedules an action on a drawable to occur at a specified time.void
scrollBy
(int x, int y) Move the scrolled position of your view.void
scrollTo
(int x, int y) Set the scrolled position of your view.void
setActivated
(boolean activated) Changes the activated state of this view.void
setAlpha
(float alpha) final void
setAnimationMatrix
(Matrix matrix) Changes the transformation matrix on the view.void
setBackground
(Drawable background) Set the background to a given Drawable, or remove the background.final void
setBottom
(int bottom) Sets the bottom position of this view relative to its parent.void
setClickable
(boolean clickable) Enables or disables click events for this view.void
setContextClickable
(boolean contextClickable) Enables or disables context clicking for this view.void
setDuplicateParentStateEnabled
(boolean enabled) Enables or disables the duplication of the parent's state into this view.void
setElevation
(float elevation) Sets the base elevation of this view, in pixels.void
setEnabled
(boolean enabled) Set the enabled state of this view.void
setFocusable
(boolean focusable) Set whether this view can receive the focus.void
setFocusable
(int focusable) Sets whether this view can receive focus.void
setFocusableInTouchMode
(boolean focusableInTouchMode) Set whether this view can receive focus while in touch mode.void
setFocusedByDefault
(boolean isFocusedByDefault) Sets whether this View should receive focus when the focus is restored for the view hierarchy containing this view.final void
Sets this View as the one which receives focus the next time cluster navigation jumps to the cluster containing this View.void
setForeground
(Drawable foreground) Supply a Drawable that is to be rendered on top of all of the content in the view.void
setForegroundGravity
(int gravity) Describes how the foreground is positioned.protected boolean
setFrame
(int left, int top, int right, int bottom) Assign a size and position to this view.void
setHapticFeedbackEnabled
(boolean hapticFeedbackEnabled) Set whether this view should have haptic feedback for events such as long presses.void
setHasTransientState
(boolean hasTransientState) Set whether this view is currently tracking transient state that the framework should attempt to preserve when possible.void
setHasTranslationTransientState
(boolean hasTranslationTransientState) Set the view is tracking translation transient state.void
setHorizontalFadingEdgeEnabled
(boolean horizontalFadingEdgeEnabled) Define whether the horizontal edges should be faded when this view is scrolled horizontally.void
setHorizontalScrollBarEnabled
(boolean enabled) Define whether the horizontal scrollbar should have or not.void
setHorizontalScrollbarThumbDrawable
(Drawable drawable) Defines the horizontal thumb drawablevoid
setHorizontalScrollbarTrackDrawable
(Drawable drawable) Defines the horizontal track drawablevoid
setHovered
(boolean hovered) Sets whether the view is currently hovered.void
setId
(int id) Sets the identifier for this view.void
setIsRootNamespace
(boolean isRoot) void
setKeyboardNavigationCluster
(boolean isCluster) Set whether this view is a root of a keyboard navigation cluster.void
setLayoutDirection
(int layoutDirection) Set the layout direction for this view.void
Set the layout parameters associated with this view.final void
setLeft
(int left) Sets the left position of this view relative to its parent.void
setLongClickable
(boolean longClickable) Enables or disables long click events for this view.protected final void
setMeasuredDimension
(int measuredWidth, int measuredHeight) Set the measured dimension, must be called byonMeasure(int, int)
void
setMinimumHeight
(int minHeight) Sets the minimum height of the view.void
setMinimumWidth
(int minWidth) Sets the minimum width of the view.void
setNestedScrollingEnabled
(boolean enabled) Enable or disable nested scrolling for this view.void
setNextClusterForwardId
(int nextClusterForwardId) Sets the id of the view to use as the root of the next keyboard navigation cluster.void
setNextFocusDownId
(int nextFocusDownId) Sets the id of the view to use when the next focus isFOCUS_DOWN
.void
setNextFocusForwardId
(int nextFocusForwardId) Sets the id of the view to use when the next focus isFOCUS_FORWARD
.void
setNextFocusLeftId
(int nextFocusLeftId) Sets the id of the view to use when the next focus isFOCUS_LEFT
.void
setNextFocusRightId
(int nextFocusRightId) Sets the id of the view to use when the next focus isFOCUS_RIGHT
.void
setNextFocusUpId
(int nextFocusUpId) Sets the id of the view to use when the next focus isFOCUS_UP
.void
Register a callback to be invoked when this view is clicked.void
Register a callback to be invoked when this view is context clicked.void
Register a callback to be invoked when the context menu for this view is being built.void
Register a drag event listener callback object for this View.void
Register a callback to be invoked when focus of this view changed.void
Register a callback to be invoked when a generic motion event is sent to this view.void
Register a callback to be invoked when a hover event is sent to this view.void
Register a callback to be invoked when a hardware key is pressed in this view.void
Register a callback to be invoked when this view is clicked and held.void
Register a callback to be invoked when the scroll X or Y positions of this view change.void
Register a callback to be invoked when a touch event is sent to this view.void
setOverScrollMode
(int overScrollMode) Set the over-scroll mode for this view.void
setPadding
(int left, int top, int right, int bottom) Sets the padding.void
setPaddingRelative
(int start, int top, int end, int bottom) Sets the relative padding.void
setPivotX
(float pivotX) void
setPivotY
(float pivotY) void
setPressed
(boolean pressed) Sets the pressed state for this view.final void
setRevealOnFocusHint
(boolean revealOnFocus) Sets this view's preference for reveal behavior when it gains focus.final void
setRight
(int right) Sets the right position of this view relative to its parent.void
setRotation
(float rotation) Sets the degrees that the view is rotated around the pivot point.void
setRotationX
(float rotationX) Sets the degrees that the view is rotated around the horizontal axis through the pivot point.void
setRotationY
(float rotationY) Sets the degrees that the view is rotated around the vertical axis through the pivot point.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.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.void
setScrollBarDefaultDelayBeforeFade
(int scrollBarDefaultDelayBeforeFade) Define the delay before scrollbars fade.void
setScrollBarFadeDuration
(int scrollBarFadeDuration) Define the scrollbar fade duration.void
setScrollbarFadingEnabled
(boolean fadeScrollbars) Define whether scrollbars will fade when the view is not scrolling.void
setScrollBarSize
(int scrollBarSize) Define the scrollbar size.void
setScrollBarStyle
(int style) Specify the style of the scrollbars.void
setScrollIndicators
(int indicators) Sets the state of all scroll indicators.void
setScrollIndicators
(int indicators, int mask) Sets the state of the scroll indicators specified by the mask.void
setScrollX
(int value) Set the horizontal scrolled position of your view.void
setScrollY
(int value) Set the vertical scrolled position of your view.void
setSelected
(boolean selected) Changes the selection state of this view.void
setSoundEffectsEnabled
(boolean soundEffectsEnabled) Set whether this view should have sound effects enabled for events such as clicking and touching.void
setStateListAnimator
(StateListAnimator stateListAnimator) Attaches the provided StateListAnimator to this View.void
Sets a tag associated with this view and a key.void
setTextAlignment
(int textAlignment) Set the text alignment.void
setTextDirection
(int textDirection) Set the text direction.void
setTooltipText
(CharSequence tooltipText) Sets the tooltip text which will be displayed in a small popup next to the view.final void
setTop
(int top) Sets the top position of this view relative to its parent.final void
setTransitionAlpha
(float alpha) This property is intended only for use by theFade
transition, which animates it to produce a visual translucency that does not side effect (or get affected by) the real alpha property.final void
setTransitionName
(String transitionName) Sets the name of the View to be used to identify Views in Transitions.final void
setTransitionVisibility
(int visibility) Changes the visibility of this View without triggering any other changes.void
setTranslationX
(float translationX) Sets the horizontal location of this view relative to itsleft
position.void
setTranslationY
(float translationY) Sets the vertical location of this view relative to itstop
position.void
setTranslationZ
(float translationZ) Sets the depth location of this view relative to itselevation
.void
setVerticalFadingEdgeEnabled
(boolean verticalFadingEdgeEnabled) Define whether the vertical edges should be faded when this view is scrolled vertically.void
setVerticalScrollBarEnabled
(boolean enabled) Define whether the vertical scrollbar should have or not.void
setVerticalScrollbarThumbDrawable
(Drawable drawable) Defines the vertical scrollbar thumb drawablevoid
setVerticalScrollbarTrackDrawable
(Drawable drawable) Defines the vertical scrollbar track drawablevoid
setVisibility
(int visibility) Set the visibility state of this view.void
setWillNotDraw
(boolean willNotDraw) If this view doesn't do any drawing on its own, set this flag to allow further optimizations.void
setX
(float x) Sets the visual x position of this view, in pixels.void
setY
(float y) Sets the visual y position of this view, in pixels.void
setZ
(float z) Sets the visual z position of this view, in pixels.final boolean
Shows the context menu for this view.boolean
showContextMenu
(float x, float y) Shows the context menu for this view anchored to the specified view-relative coordinate.final int
sp
(float value) Utility to get the size in pixels that matches the text layout standards.final ActionMode
startActionMode
(ActionMode.Callback callback) Start an action mode with the default typeActionMode.TYPE_PRIMARY
.startActionMode
(ActionMode.Callback callback, int type) Start an action mode with the given type.final boolean
startDragAndDrop
(Object localState, View.DragShadow shadow, int flags) Starts a drag and drop operation.boolean
startNestedScroll
(int axes, int type) Begin a nestable scroll operation along the given axes, for the given input type.void
stopNestedScroll
(int type) Stop a nested scroll in progress for the given input type.boolean
Transforms a motion event from view-local coordinates to on-screen coordinates.boolean
Transforms a motion event from on-screen coordinates to view-local coordinates.toString()
void
transformFromViewToWindowSpace
(int[] inOutLocation) void
transformMatrixToGlobal
(Matrix matrix) Modifies the input matrix such that it maps view-local coordinates to on-screen coordinates.void
transformMatrixToLocal
(Matrix matrix) Modifies the input matrix such that it maps on-screen coordinates to view-local coordinates.final void
Unschedule any events associated with the given Drawable.final void
unscheduleDrawable
(Drawable who, Runnable what) Cancels a scheduled action on a drawable.protected boolean
verifyDrawable
(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.boolean
Returns whether this View draws on its own.
-
Field Details
-
VIEW_MARKER
protected static final org.apache.logging.log4j.Marker VIEW_MARKERThe logging marker used by this class withLogger
. -
NO_ID
public static final int NO_IDUsed to mark a View that has no ID.- See Also:
-
NOT_FOCUSABLE
public static final int NOT_FOCUSABLEThis view does not want keystrokes.Use with
setFocusable(int)
.- See Also:
-
FOCUSABLE
public static final int FOCUSABLEThis view wants keystrokes.Use with
setFocusable(int)
.- See Also:
-
FOCUSABLE_AUTO
public static final int FOCUSABLE_AUTOThis view determines focusability automatically. This is the default.Use with
setFocusable(int)
.- See Also:
-
VISIBLE
public static final int VISIBLEThis view is visible. Use withsetVisibility(int)
.- See Also:
-
INVISIBLE
public static final int INVISIBLEThis view is invisible, but it still takes up space for layout purposes. Use withsetVisibility(int)
.- See Also:
-
GONE
public static final int GONEThis view is invisible, and it doesn't take any space for layout purposes. Use withsetVisibility(int)
.- See Also:
-
SCROLLBARS_INSIDE_OVERLAY
public static final int SCROLLBARS_INSIDE_OVERLAYThe scrollbar style to display the scrollbars inside the content area, without increasing the padding. The scrollbars will be overlaid with translucency on the view's content.- See Also:
-
SCROLLBARS_INSIDE_INSET
public static final int SCROLLBARS_INSIDE_INSETThe scrollbar style to display the scrollbars inside the padded area, increasing the padding of the view. The scrollbars will not overlap the content area of the view.- See Also:
-
SCROLLBARS_OUTSIDE_OVERLAY
public static final int SCROLLBARS_OUTSIDE_OVERLAYThe scrollbar style to display the scrollbars at the edge of the view, without increasing the padding. The scrollbars will be overlaid with translucency.- See Also:
-
SCROLLBARS_OUTSIDE_INSET
public static final int SCROLLBARS_OUTSIDE_INSETThe scrollbar style to display the scrollbars at the edge of the view, increasing the padding of the view. The scrollbars will only overlap the background, if any.- See Also:
-
SOUND_EFFECTS_ENABLED
public static final int SOUND_EFFECTS_ENABLEDView flag indicating whether this view should have sound effects enabled for events such as clicking and touching.- See Also:
-
HAPTIC_FEEDBACK_ENABLED
public static final int HAPTIC_FEEDBACK_ENABLEDView flag indicating whether this view should have haptic feedback enabled for events such as long presses.- See Also:
-
FOCUSABLES_ALL
public static final int FOCUSABLES_ALLView flag indicating whetheraddFocusables(ArrayList, int, int)
should add all focusable Views regardless if they are focusable in touch mode.- See Also:
-
FOCUSABLES_TOUCH_MODE
public static final int FOCUSABLES_TOUCH_MODEView flag indicating whetheraddFocusables(ArrayList, int, int)
should add only Views focusable in touch mode.- See Also:
-
FOCUS_BACKWARD
public static final int FOCUS_BACKWARDUse withfocusSearch(int)
. Move focus to the previous selectable item.- See Also:
-
FOCUS_FORWARD
public static final int FOCUS_FORWARDUse withfocusSearch(int)
. Move focus to the next selectable item.- See Also:
-
FOCUS_LEFT
public static final int FOCUS_LEFTUse withfocusSearch(int)
. Move focus to the left.- See Also:
-
FOCUS_UP
public static final int FOCUS_UPUse withfocusSearch(int)
. Move focus up.- See Also:
-
FOCUS_RIGHT
public static final int FOCUS_RIGHTUse withfocusSearch(int)
. Move focus to the right.- See Also:
-
FOCUS_DOWN
public static final int FOCUS_DOWNUse withfocusSearch(int)
. Move focus down.- See Also:
-
MEASURED_SIZE_MASK
public static final int MEASURED_SIZE_MASKBits ofgetMeasuredWidthAndState()
andgetMeasuredWidthAndState()
that provide the actual measured size.- See Also:
-
MEASURED_STATE_MASK
public static final int MEASURED_STATE_MASKBits ofgetMeasuredWidthAndState()
andgetMeasuredWidthAndState()
that provide the additional state bits.- See Also:
-
MEASURED_HEIGHT_STATE_SHIFT
public static final int MEASURED_HEIGHT_STATE_SHIFTBit shift ofMEASURED_STATE_MASK
to get to the height bits for functions that combine both width and height into a single int, such asgetMeasuredState()
and the childState argument ofresolveSizeAndState(int, int, int)
.- See Also:
-
MEASURED_STATE_TOO_SMALL
public static final int MEASURED_STATE_TOO_SMALLBit ofgetMeasuredWidthAndState()
andgetMeasuredWidthAndState()
that indicates the measured size is smaller that the space the view would like to have.- See Also:
-
EMPTY_STATE_SET
protected static final int[] EMPTY_STATE_SETIndicates the view has no states set. States are used withDrawable
to change the drawing of the view depending on its state.- See Also:
-
ENABLED_STATE_SET
protected static final int[] ENABLED_STATE_SETIndicates the view is enabled. States are used withDrawable
to change the drawing of the view depending on its state.- See Also:
-
FOCUSED_STATE_SET
protected static final int[] FOCUSED_STATE_SETIndicates the view is focused. States are used withDrawable
to change the drawing of the view depending on its state.- See Also:
-
SELECTED_STATE_SET
protected static final int[] SELECTED_STATE_SETIndicates the view is selected. States are used withDrawable
to change the drawing of the view depending on its state.- See Also:
-
PRESSED_STATE_SET
protected static final int[] PRESSED_STATE_SETIndicates the view is pressed. States are used withDrawable
to change the drawing of the view depending on its state.- See Also:
-
WINDOW_FOCUSED_STATE_SET
protected static final int[] WINDOW_FOCUSED_STATE_SETIndicates the view's window has focus. States are used withDrawable
to change the drawing of the view depending on its state.- See Also:
-
ENABLED_FOCUSED_STATE_SET
protected static final int[] ENABLED_FOCUSED_STATE_SETIndicates the view is enabled and has the focus.- See Also:
-
ENABLED_SELECTED_STATE_SET
protected static final int[] ENABLED_SELECTED_STATE_SETIndicates the view is enabled and selected.- See Also:
-
ENABLED_WINDOW_FOCUSED_STATE_SET
protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SETIndicates the view is enabled and that its window has focus.- See Also:
-
FOCUSED_SELECTED_STATE_SET
protected static final int[] FOCUSED_SELECTED_STATE_SETIndicates the view is focused and selected.- See Also:
-
FOCUSED_WINDOW_FOCUSED_STATE_SET
protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SETIndicates the view has the focus and that its window has the focus.- See Also:
-
SELECTED_WINDOW_FOCUSED_STATE_SET
protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SETIndicates the view is selected and that its window has the focus.- See Also:
-
ENABLED_FOCUSED_SELECTED_STATE_SET
protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SETIndicates the view is enabled, focused and selected.- See Also:
-
ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET
protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SETIndicates the view is enabled, focused and its window has the focus.- See Also:
-
ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET
protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SETIndicates the view is enabled, selected and its window has the focus.- See Also:
-
FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET
protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SETIndicates the view is focused, selected and its window has the focus.- See Also:
-
ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET
protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SETIndicates the view is enabled, focused, selected and its window has the focus.- See Also:
-
PRESSED_WINDOW_FOCUSED_STATE_SET
protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SETIndicates the view is pressed and its window has the focus.- See Also:
-
PRESSED_SELECTED_STATE_SET
protected static final int[] PRESSED_SELECTED_STATE_SETIndicates the view is pressed and selected.- See Also:
-
PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET
protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SETIndicates the view is pressed, selected and its window has the focus.- See Also:
-
PRESSED_FOCUSED_STATE_SET
protected static final int[] PRESSED_FOCUSED_STATE_SETIndicates the view is pressed and focused.- See Also:
-
PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET
protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SETIndicates the view is pressed, focused and its window has the focus.- See Also:
-
PRESSED_FOCUSED_SELECTED_STATE_SET
protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SETIndicates the view is pressed, focused and selected.- See Also:
-
PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET
protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SETIndicates the view is pressed, focused, selected and its window has the focus.- See Also:
-
PRESSED_ENABLED_STATE_SET
protected static final int[] PRESSED_ENABLED_STATE_SETIndicates the view is pressed and enabled.- See Also:
-
PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET
protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SETIndicates the view is pressed, enabled and its window has the focus.- See Also:
-
PRESSED_ENABLED_SELECTED_STATE_SET
protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SETIndicates the view is pressed, enabled and selected.- See Also:
-
PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET
protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SETIndicates the view is pressed, enabled, selected and its window has the focus.- See Also:
-
PRESSED_ENABLED_FOCUSED_STATE_SET
protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SETIndicates the view is pressed, enabled and focused.- See Also:
-
PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET
protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SETIndicates the view is pressed, enabled, focused and its window has the focus.- See Also:
-
PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET
protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SETIndicates the view is pressed, enabled, focused and selected.- See Also:
-
PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET
protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SETIndicates the view is pressed, enabled, focused, selected and its window has the focus.- See Also:
-
LAYOUT_DIRECTION_UNDEFINED
@Internal public static final int LAYOUT_DIRECTION_UNDEFINEDA flag to indicate that the layout direction of this view has not been defined yet.- See Also:
-
LAYOUT_DIRECTION_LTR
public static final int LAYOUT_DIRECTION_LTRHorizontal layout direction of this view is from Left to Right. Use withsetLayoutDirection(int)
.- See Also:
-
LAYOUT_DIRECTION_RTL
public static final int LAYOUT_DIRECTION_RTLHorizontal layout direction of this view is from Right to Left. Use withsetLayoutDirection(int)
.- See Also:
-
LAYOUT_DIRECTION_INHERIT
public static final int LAYOUT_DIRECTION_INHERITHorizontal layout direction of this view is inherited from its parent. Use withsetLayoutDirection(int)
.- See Also:
-
LAYOUT_DIRECTION_LOCALE
public static final int LAYOUT_DIRECTION_LOCALEHorizontal layout direction of this view is from deduced from the default language script for the locale. Use withsetLayoutDirection(int)
.- See Also:
-
TEXT_DIRECTION_INHERIT
public static final int TEXT_DIRECTION_INHERITText direction is inherited throughViewGroup
- See Also:
-
TEXT_DIRECTION_FIRST_STRONG
public static final int TEXT_DIRECTION_FIRST_STRONGText direction is using "first strong algorithm". The first strong directional character determines the paragraph direction. If there is no strong directional character, the paragraph direction is the view's resolved layout direction.- See Also:
-
TEXT_DIRECTION_ANY_RTL
public static final int TEXT_DIRECTION_ANY_RTLText direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. If there are neither, the paragraph direction is the view's resolved layout direction.- See Also:
-
TEXT_DIRECTION_LTR
public static final int TEXT_DIRECTION_LTRText direction is forced to LTR.- See Also:
-
TEXT_DIRECTION_RTL
public static final int TEXT_DIRECTION_RTLText direction is forced to RTL.- See Also:
-
TEXT_DIRECTION_LOCALE
public static final int TEXT_DIRECTION_LOCALEText direction is coming from the system Locale.- See Also:
-
TEXT_DIRECTION_FIRST_STRONG_LTR
public static final int TEXT_DIRECTION_FIRST_STRONG_LTRText direction is using "first strong algorithm". The first strong directional character determines the paragraph direction. If there is no strong directional character, the paragraph direction is LTR.- See Also:
-
TEXT_DIRECTION_FIRST_STRONG_RTL
public static final int TEXT_DIRECTION_FIRST_STRONG_RTLText direction is using "first strong algorithm". The first strong directional character determines the paragraph direction. If there is no strong directional character, the paragraph direction is RTL.- See Also:
-
TEXT_ALIGNMENT_INHERIT
public static final int TEXT_ALIGNMENT_INHERITDefault text alignment. The text alignment of this View is inherited from its parent. Use withsetTextAlignment(int)
- See Also:
-
TEXT_ALIGNMENT_GRAVITY
public static final int TEXT_ALIGNMENT_GRAVITYDefault for the root view. The gravity determines the text alignment, ALIGN_NORMAL, ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph's text direction.Use with
setTextAlignment(int)
- See Also:
-
TEXT_ALIGNMENT_TEXT_START
public static final int TEXT_ALIGNMENT_TEXT_STARTAlign to the start of the paragraph, e.g. ALIGN_NORMAL.Use with
setTextAlignment(int)
- See Also:
-
TEXT_ALIGNMENT_TEXT_END
public static final int TEXT_ALIGNMENT_TEXT_ENDAlign to the end of the paragraph, e.g. ALIGN_OPPOSITE.Use with
setTextAlignment(int)
- See Also:
-
TEXT_ALIGNMENT_CENTER
public static final int TEXT_ALIGNMENT_CENTERCenter the paragraph, e.g. ALIGN_CENTER.Use with
setTextAlignment(int)
- See Also:
-
TEXT_ALIGNMENT_VIEW_START
public static final int TEXT_ALIGNMENT_VIEW_STARTAlign to the start of the view, which is ALIGN_LEFT if the view's resolved layoutDirection is LTR, and ALIGN_RIGHT otherwise.Use with
setTextAlignment(int)
- See Also:
-
TEXT_ALIGNMENT_VIEW_END
public static final int TEXT_ALIGNMENT_VIEW_ENDAlign to the end of the view, which is ALIGN_RIGHT if the view's resolved layoutDirection is LTR, and ALIGN_LEFT otherwise.Use with
setTextAlignment(int)
- See Also:
-
SCROLL_INDICATOR_TOP
public static final int SCROLL_INDICATOR_TOPScroll indicator direction for the top edge of the view.- See Also:
-
SCROLL_INDICATOR_BOTTOM
public static final int SCROLL_INDICATOR_BOTTOMScroll indicator direction for the bottom edge of the view.- See Also:
-
SCROLL_INDICATOR_LEFT
public static final int SCROLL_INDICATOR_LEFTScroll indicator direction for the left edge of the view.- See Also:
-
SCROLL_INDICATOR_RIGHT
public static final int SCROLL_INDICATOR_RIGHTScroll indicator direction for the right edge of the view.- See Also:
-
SCROLL_INDICATOR_START
public static final int SCROLL_INDICATOR_STARTScroll indicator direction for the starting edge of the view.Resolved according to the view's layout direction, see
getLayoutDirection()
for more information.- See Also:
-
SCROLL_INDICATOR_END
public static final int SCROLL_INDICATOR_ENDScroll indicator direction for the ending edge of the view.Resolved according to the view's layout direction, see
getLayoutDirection()
for more information.- See Also:
-
OVER_SCROLL_ALWAYS
public static final int OVER_SCROLL_ALWAYSAlways allow a user to over-scroll this view, provided it is a view that can scroll.- See Also:
-
OVER_SCROLL_IF_CONTENT_SCROLLS
public static final int OVER_SCROLL_IF_CONTENT_SCROLLSAllow a user to over-scroll this view only if the content is large enough to meaningfully scroll, provided it is a view that can scroll.- See Also:
-
OVER_SCROLL_NEVER
public static final int OVER_SCROLL_NEVERNever allow a user to over-scroll this view.- See Also:
-
SCROLL_AXIS_NONE
public static final int SCROLL_AXIS_NONEIndicates no axis of view scrolling.- See Also:
-
SCROLL_AXIS_HORIZONTAL
public static final int SCROLL_AXIS_HORIZONTALIndicates scrolling along the horizontal axis.- See Also:
-
SCROLL_AXIS_VERTICAL
public static final int SCROLL_AXIS_VERTICALIndicates scrolling along the vertical axis.- See Also:
-
TYPE_TOUCH
public static final int TYPE_TOUCHIndicates that the input type for the gesture is from a user touching the screen.- See Also:
-
TYPE_NON_TOUCH
public static final int TYPE_NON_TOUCHIndicates that the input type for the gesture is caused by something which is not a user touching a screen. This is usually from a fling which is settling.- See Also:
-
mScrollX
protected int mScrollXThe offset, in pixels, by which the content of this view is scrolled horizontally. Please usegetScrollX()
andsetScrollX(int)
instead of accessing these directly. -
mScrollY
protected int mScrollYThe offset, in pixels, by which the content of this view is scrolled vertically. Please usegetScrollY()
andsetScrollY(int)
instead of accessing these directly. -
mPaddingLeft
protected int mPaddingLeftThe final computed left padding in pixels that is used for drawing. This is the distance in pixels between the left edge of this view and the left edge of its content. -
mPaddingRight
protected int mPaddingRightThe final computed right padding in pixels that is used for drawing. This is the distance in pixels between the right edge of this view and the right edge of its content. -
mPaddingTop
protected int mPaddingTopThe final computed top padding in pixels that is used for drawing. This is the distance in pixels between the top edge of this view and the top edge of its content. -
mPaddingBottom
protected int mPaddingBottomThe final computed bottom padding in pixels that is used for drawing. This is the distance in pixels between the bottom edge of this view and the bottom edge of its content. -
ALPHA
A Property wrapper around thealpha
functionality handled by thesetAlpha(float)
andgetAlpha()
methods. -
TRANSLATION_X
A Property wrapper around thetranslationX
functionality handled by thesetTranslationX(float)
andgetTranslationX()
methods. -
TRANSLATION_Y
A Property wrapper around thetranslationY
functionality handled by thesetTranslationY(float)
andgetTranslationY()
methods. -
TRANSLATION_Z
A Property wrapper around thetranslationZ
functionality handled by thesetTranslationZ(float)
andgetTranslationZ()
methods. -
X
-
Y
-
Z
-
ROTATION
A Property wrapper around therotation
functionality handled by thesetRotation(float)
andgetRotation()
methods. -
ROTATION_X
A Property wrapper around therotationX
functionality handled by thesetRotationX(float)
andgetRotationX()
methods. -
ROTATION_Y
A Property wrapper around therotationY
functionality handled by thesetRotationY(float)
andgetRotationY()
methods. -
SCALE_X
A Property wrapper around thescaleX
functionality handled by thesetScaleX(float)
andgetScaleX()
methods. -
SCALE_Y
A Property wrapper around thescaleY
functionality handled by thesetScaleY(float)
andgetScaleY()
methods. -
LEFT
-
TOP
-
RIGHT
A Property wrapper around theright
functionality handled by thesetRight(int)
andgetRight()
methods. -
BOTTOM
A Property wrapper around thebottom
functionality handled by thesetBottom(int)
andgetBottom()
methods. -
SCROLL_X
A Property wrapper around thescrollX
functionality handled by thesetScrollX(int)
andgetScrollX()
methods. -
SCROLL_Y
A Property wrapper around thescrollY
functionality handled by thesetScrollY(int)
andgetScrollY()
methods.
-
-
Constructor Details
-
View
Simple constructor to use when creating a view from code.
-
-
Method Details
-
isShowingLayoutBounds
public final boolean isShowingLayoutBounds()Returnstrue
when the View is attached and the system developer setting to show the layout bounds is enabled orfalse
otherwise. -
draw
Base method that directly draws this view and its background, foreground, overlay and all children to the given canvas. When implementing a view, overrideonDraw(Canvas)
instead of this.This is not the entry point for the view system to draw.
- Parameters:
canvas
- the canvas to draw content
-
onDraw
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
Draw the child views.- Parameters:
canvas
- the canvas to draw content
-
onDrawForeground
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
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 parentt
- top position, relative to parentr
- right position, relative to parentb
- bottom position, relative to parent
-
onLayout
protected void onLayout(boolean changed, int left, int top, int right, int bottom) Called fromlayout(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 viewleft
- Left position, relative to parenttop
- Top position, relative to parentright
- Right position, relative to parentbottom
- 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 parenttop
- top position, relative to parentright
- right position, relative to parentbottom
- 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 widthheight
- new heightprevWidth
- previous widthprevHeight
- 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 parentheightMeasureSpec
- height measure specification imposed by the parent- Throws:
IllegalStateException
- measured dimension is not set inonMeasure(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 bymeasure(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 anIllegalStateException
, thrown bymeasure(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 parentMeasureSpec
heightMeasureSpec
- height measure specification imposed by the parentMeasureSpec
-
setMeasuredDimension
protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) Set the measured dimension, must be called byonMeasure(int, int)
- Parameters:
measuredWidth
- the measured width of this viewmeasuredHeight
- the measured height of this view
-
getMeasuredWidth
public final int getMeasuredWidth()LikegetMeasuredWidthAndState()
, but only returns the raw width component (that is the result is masked byMEASURED_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 tomeasure(int, int)
. This result is a bit mask as defined byMEASURED_SIZE_MASK
andMEASURED_STATE_TOO_SMALL
. This should be used during measurement and layout calculations only. UsegetWidth()
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()LikegetMeasuredHeightAndState()
, but only returns the raw height component (that is the result is masked byMEASURED_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 tomeasure(int, int)
. This result is a bit mask as defined byMEASURED_SIZE_MASK
andMEASURED_STATE_TOO_SMALL
. This should be used during measurement and layout calculations only. UsegetHeight()
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 ofgetMeasuredWidthAndState()
andgetMeasuredHeightAndState()
, combined into one integer. The width component is in the regular bitsMEASURED_STATE_MASK
and the height component is at the shifted bitsMEASURED_HEIGHT_STATE_SHIFT
>>MEASURED_STATE_MASK
. -
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
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 bygetMeasuredState()
.- 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 ofresolveSizeAndState(int, int, int)
returning only theMEASURED_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 theMEASURED_SIZE_MASK
bits and optionally the bitMEASURED_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
andMEASURED_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 viewmeasureSpec
- 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
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 insetId(int)
. The range is from 0x10000 to 0xFFFFFF.- Returns:
- a generated ID value
-
getTag
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
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 tagtag
- 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. -
setVisibility
public void setVisibility(int visibility) Set the visibility state of this view. -
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
, orFOCUSABLE_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 ofNOT_FOCUSABLE
,FOCUSABLE
, orFOCUSABLE_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. UnlesssetPressed(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
Invalidates the specified Drawable.- Specified by:
invalidateDrawable
in interfaceDrawable.Callback
- Parameters:
drawable
- the drawable to invalidate
-
scheduleDrawable
Schedules an action on a drawable to occur at a specified time.- Specified by:
scheduleDrawable
in interfaceDrawable.Callback
- Parameters:
who
- the recipient of the actionwhat
- the action to run on the drawablewhen
- the time at which the action must occur. Uses theCore.timeMillis()
timebase.
-
unscheduleDrawable
Cancels a scheduled action on a drawable.- Specified by:
unscheduleDrawable
in interfaceDrawable.Callback
- Parameters:
who
- the recipient of the actionwhat
- the action to cancel
-
unscheduleDrawable
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
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
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 fardirection
- The direction of the focus
-
addFocusables
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.
-
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
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 argumentsFOCUS_DOWN
andnull
.- 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 callingrequestFocus(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)
withnull
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
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 toViewGroup.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 internalView
that it wishes to forward the request to.- Parameters:
direction
- One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHTpreviouslyFocusedRect
- The rectangle (in this View's coordinate system) to give a finer grained hint about where focus is coming from. May be null if there is no hint.- Returns:
- Whether 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
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
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 spaceimmediate
- 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:
-
clearFocus
public void clearFocus()Called when this view wants to give up focus. If focus is clearedonFocusChanged(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 returnstrue
. A "reachable hasFocusable()" is a view whose parents do not block descendants focus. OnlyVISIBLE
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 returnstrue
. A "reachable hasExplicitFocusable()" is a view whose parents do not block descendants focus. OnlyVISIBLE
views for whichgetFocusable()
would returnFOCUSABLE
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 areFOCUS_UP
,FOCUS_DOWN
,FOCUS_LEFT
,FOCUS_RIGHT
,FOCUS_FORWARD
, orFOCUS_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 benull
otherwise.
-
isFocused
public boolean isFocused()Returns true if this view has focus- Returns:
- True if this view has focus, false otherwise.
-
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
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.
-
getNextFocusLeftId
public int getNextFocusLeftId()Gets the id of the view to use when the next focus isFOCUS_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 isFOCUS_LEFT
.- Parameters:
nextFocusLeftId
- The next focus ID, orNO_ID
if the framework should decide automatically.
-
getNextFocusRightId
public int getNextFocusRightId()Gets the id of the view to use when the next focus isFOCUS_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 isFOCUS_RIGHT
.- Parameters:
nextFocusRightId
- The next focus ID, orNO_ID
if the framework should decide automatically.
-
getNextFocusUpId
public int getNextFocusUpId()Gets the id of the view to use when the next focus isFOCUS_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 isFOCUS_UP
.- Parameters:
nextFocusUpId
- The next focus ID, orNO_ID
if the framework should decide automatically.
-
getNextFocusDownId
public int getNextFocusDownId()Gets the id of the view to use when the next focus isFOCUS_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 isFOCUS_DOWN
.- Parameters:
nextFocusDownId
- The next focus ID, orNO_ID
if the framework should decide automatically.
-
getNextFocusForwardId
public int getNextFocusForwardId()Gets the id of the view to use when the next focus isFOCUS_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 isFOCUS_FORWARD
.- Parameters:
nextFocusForwardId
- The next focus ID, orNO_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, orNO_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
Defines the vertical scrollbar thumb drawable- See Also:
-
setVerticalScrollbarTrackDrawable
Defines the vertical scrollbar track drawable- See Also:
-
setHorizontalScrollbarThumbDrawable
Defines the horizontal thumb drawable- See Also:
-
setHorizontalScrollbarTrackDrawable
Defines the horizontal track drawable- See Also:
-
getVerticalScrollbarThumbDrawable
Returns the currently configured Drawable for the thumb of the vertical scroll bar if it exists, null otherwise.- See Also:
-
getVerticalScrollbarTrackDrawable
Returns the currently configured Drawable for the track of the vertical scroll bar if it exists, null otherwise.- See Also:
-
getHorizontalScrollbarThumbDrawable
Returns the currently configured Drawable for the thumb of the horizontal scroll bar if it exists, null otherwise.- See Also:
-
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 toonScrollChanged(int, int, int, int)
and the view will be invalidated.- Parameters:
x
- the x position to scroll toy
- 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 toonScrollChanged(int, int, int, int)
and the view will be invalidated.- Parameters:
x
- the amount of pixels to scroll by horizontallyy
- 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()
andisVerticalScrollBarEnabled()
. When the animation is started, this method returns true, and false otherwise. If the animation is started, this method callsinvalidate()
; in that case the caller should not callinvalidate()
.This method should be invoked every time a subclass directly updates the scroll parameters.
This method is automatically invoked by
scrollBy(int, int)
andscrollTo(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()
andisVerticalScrollBarEnabled()
. When the animation is started, this method returns true, and false otherwise. If the animation is started, this method callsinvalidate()
; in that case the caller should not callinvalidate()
.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 toonScrollChanged(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 toonScrollChanged(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()
andcomputeHorizontalScrollOffset()
.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()
andcomputeHorizontalScrollExtent()
.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()
andcomputeHorizontalScrollOffset()
.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()
andcomputeVerticalScrollOffset()
.- 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()
andcomputeVerticalScrollExtent()
.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()
andcomputeVerticalScrollOffset()
.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, or0
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, seesetScrollIndicators(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
, orFADING_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 ofscrollBy(int, int)
orscrollTo(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 overrideonOverScrolled(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 pixelsdeltaY
- Change in Y in pixelsscrollX
- Current X scroll value in pixels before applying deltaXscrollY
- Current Y scroll value in pixels before applying deltaYscrollRangeX
- Maximum content scroll range along the X axisscrollRangeY
- Maximum content scroll range along the Y axismaxOverScrollX
- 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 byoverScrollBy(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 pixelsscrollY
- New Y scroll value in pixelsclampedX
- True if scrollX was clamped to an over-scroll boundaryclampedY
- 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 ofOVER_SCROLL_ALWAYS
,OVER_SCROLL_IF_CONTENT_SCROLLS
(allow over-scrolling only if the view content is larger than the container), orOVER_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 areOVER_SCROLL_ALWAYS
,OVER_SCROLL_IF_CONTENT_SCROLLS
(allow over-scrolling only if the view content is larger than the container), orOVER_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 asViewParent.requestDisallowInterceptTouchEvent(boolean)
. In the event of programmatic scrolling the caller must explicitly callstopNestedScroll(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. SeeViewParent.onNestedScroll(View, int, int, int, int, int, int[])
.- Parameters:
axes
- Flags consisting of a combination ofSCROLL_AXIS_HORIZONTAL
and/orSCROLL_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 stepdyConsumed
- Vertical distance in pixels consumed by this view during this scroll stepdxUnconsumed
- Horizontal scroll distance in pixels not consumed by this viewdyUnconsumed
- Horizontal scroll distance in pixels not consumed by this viewoffsetInWindow
- 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 eventconsumed
- 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 pixelsdy
- Vertical scroll distance in pixelsconsumed
- 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 theminimum 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 secondvelocityY
- Vertical fling velocity in pixels per secondconsumed
- 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 returnstrue
, 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 secondvelocityY
- Vertical fling velocity in pixels per second- Returns:
- true if a nested scrolling parent consumed the fling
- If a custom view is paged and needs to settle to a fixed page-point, do not
call
-
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
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 assetScaleX(float)
orsetRotation(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
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 assetTranslationX(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
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 thetranslationX
property plus the currentleft
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 thetranslationX
property to be the difference between the x value passed in and the currentleft
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 thetranslationY
property plus the currenttop
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 thetranslationY
property to be the difference between the y value passed in and the currenttop
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 thetranslationZ
property plus the currentelevation
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 thetranslationZ
property to be the difference between the z value passed in and the currentelevation
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 itsleft
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 itsleft
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 itstop
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 itstop
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 itselevation
.- 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 itselevation
. -
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()- 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 isrotated
andscaled
. 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()- 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 isrotated
andscaled
. 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 tosetPivotX(float)
orsetPivotY(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 tosetPivotX(float)
orsetPivotY(float)
. After calling thisisPivotSet()
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 (seehasOverlappingRendering()
for more details on this behavior). Calling this method is an alternative to overridinghasOverlappingRendering()
in a subclass, providing the value which is then used internally. That is, when this method is called, the value ofhasOverlappingRendering()
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 byhasOverlappingRendering()
.
-
getHasOverlappingRendering
public final boolean getHasOverlappingRendering()Returns the value for overlapping rendering that is used internally. This is either the value passed intoforceHasOverlappingRendering(boolean)
, if called, or the return value ofhasOverlappingRendering()
, 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 theFade
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 theFade
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
Changes the transformation matrix on the view. This is used in animation frameworks, such asTransition
. When the animation finishes, the matrix should be cleared by calling this method withnull
as the matrix parameter. Application developers should use transformation methods likesetRotation(float)
,setScaleX(float)
,setScaleX(float)
,setTranslationX(float)
} andsetTranslationY(float)
instead.- Parameters:
matrix
- The matrix, null indicates that the matrix should be cleared.- See Also:
-
getAnimationMatrix
Changes the transition matrix on the view. This is only used in the transition animation framework,Transition
. Returnsnull
when there is no transformation provided bysetAnimationMatrix(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
Returns the current StateListAnimator if exists.- Returns:
- StateListAnimator or null if it does not exist
- See Also:
-
setStateListAnimator
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
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 beforeonDraw(Canvas)
, however it may be called any time before the first onDraw -- including before or afteronMeasure(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 tocancelPendingInputEvents()
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)
orHandler
should override this method, callsuper.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 inSoundEffectConstants
.
-
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 inHapticFeedbackConstants
-
performHapticFeedback
public boolean performHapticFeedback(int feedbackConstant, int flags) BZZZTT!!1!Like
performHapticFeedback(int)
, with additional options.- Parameters:
feedbackConstant
- One of the constants defined inHapticFeedbackConstants
flags
- Additional flags as perHapticFeedbackConstants
.
-
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
orLAYOUT_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 returnsLAYOUT_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 withsetTextDirection(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 withsetTextAlignment(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 callingrequestLayout()
during a layout pass.- Returns:
- whether the view hierarchy is currently undergoing a layout pass
-
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
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 coordinatey
- hotspot y coordinate
-
dispatchDrawableHotspotChanged
public void dispatchDrawableHotspotChanged(float x, float y) Dispatches drawableHotspotChanged to all of this View's children.- Parameters:
x
- hotspot x coordinatey
- 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 fromgetPaddingLeft()
,getPaddingTop()
,getPaddingRight()
andgetPaddingBottom()
may be different from the values set in this call.- Parameters:
left
- the left padding in pixelstop
- the top padding in pixelsright
- the right padding in pixelsbottom
- 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 fromgetPaddingStart()
,getPaddingTop()
,getPaddingEnd()
andgetPaddingBottom()
may be different from the values set in this call.- Parameters:
start
- the start padding in pixelstop
- the top padding in pixelsend
- the end padding in pixelsbottom
- 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 valuessetPaddingRelative(int, int, int, int)
or through- Returns:
- true if the padding is relative or false if it is not.
-
verifyDrawable
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
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
Generate the newDrawable
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 usegetDrawableState()
.- 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 byonCreateDrawableState(int)
.- Parameters:
baseState
- The base state values returned byonCreateDrawableState(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
CallDrawable.jumpToCurrentState()
on all Drawable objects associated with this view.Also calls
StateListAnimator.jumpToCurrentState()
if there is a StateListAnimator attached to this view. -
setBackground
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
Gets the background drawable- Returns:
- The drawable used as the background for this view, if any.
- See Also:
-
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
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
- seeGravity
- See Also:
-
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
Finds the topmost view in the current view hierarchy.- Returns:
- the topmost view containing this view
-
toGlobalMotionEvent
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
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
Modifies the input matrix such that it maps view-local coordinates to on-screen coordinates.- Parameters:
matrix
- input matrix to modify
-
transformMatrixToLocal
Modifies the input matrix such that it maps on-screen coordinates to view-local coordinates.- Parameters:
matrix
- input matrix to modify
-
getBoundsOnScreen
Gets the location of this view in screen coordinates.- Parameters:
outRect
- The output location
-
getBoundsOnScreen
Gets the location of this view in screen coordinates.- Parameters:
outRect
- The output locationclipToParent
- Whether to clip child bounds to the parent ones.
-
mapRectFromViewToScreenCoords
Map a rectangle from view-relative coordinates to screen-relative coordinates- Parameters:
rect
- The rectangle to be mappedclipToParent
- 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
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
-
findViewById
Finds the first descendant view with the given ID, the view itself if the ID matchesgetId()
, ornull
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
Finds the first descendant view with the given ID, the view itself if the ID matchesgetId()
, 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
- Parameters:
id
- the id of the view to be found- Returns:
- the view of the specified id, null if cannot be found
-
findViewByPredicate
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
- Returns:
- A handler associated with the thread running the View. This handler can be used to pump events in the UI events queue.
-
getViewRoot
Gets the view root associated with the View.- Returns:
- The view root, or null if none.
-
post
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
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
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
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 executeddelayMillis
- the delay (in milliseconds) until the runnable will be executed- See Also:
-
removeCallbacks
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 aView.DragShadow
object to the window system. The system callsView.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'sonDragEvent(DragEvent)
method. Both are passed aDragEvent
object that has aDragEvent.getAction()
value ofDragEvent.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
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
Dispatch a view visibility change down the view hierarchy. ViewGroups should override to route to their children. -
onVisibilityChanged
Called when the visibility of the view or an ancestor of the view has changed. -
getWindowVisibility
public final int getWindowVisibility()Returns the current visibility of the window this view is attached to (eitherGONE
,INVISIBLE
, orVISIBLE
).- 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 (betweenGONE
,INVISIBLE
, andVISIBLE
). 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
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 areVISIBLE
and this view's window is also visible
-
dispatchPointerEvent
Dispatch a pointer event.Dispatches touch related pointer events to
onTouchEvent(MotionEvent)
and all other events toonGenericMotionEvent(MotionEvent)
. This separation of concerns reinforces the invariant thatonTouchEvent(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
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
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
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
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
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
, orMotionEvent.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:
- The view receives a hover event with action
-
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 byisHovered()
.- See Also:
-
setOnScrollChangeListener
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
Register a callback to be invoked when focus of this view changed.- Parameters:
l
- The callback that will run.
-
addOnLayoutChangeListener
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
Remove a listener for layout changes.- Parameters:
listener
- The listener for layout bounds change.
-
addOnAttachStateChangeListener
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
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
Returns the focus-change callback registered for this view.- Returns:
- The callback, or null if one is not registered.
-
setOnClickListener
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
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
- Returns:
- the registered
View.OnLongClickListener
if there is one,null
otherwise.
-
setOnContextClickListener
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
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
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
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
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
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
Register a drag event listener callback object for this View. The parameter is an implementation ofView.OnDragListener
. To send a drag event to a View, the system calls theView.OnDragListener.onDrag(View, DragEvent)
method.- Parameters:
l
- An implementation ofView.OnDragListener
.
-
canReceivePointerEvents
protected boolean canReceivePointerEvents()Returns whether this view can receive pointer events.- Returns:
true
if this view can receive pointer events.
-
dispatchTouchEvent
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
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
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. UnlikeperformClick()
, 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. -
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 clicky
- 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
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, orFloat.NaN
to disable anchoringy
- the Y coordinate in pixels relative to the view to which the menu should be anchored, orFloat.NaN
to disable anchoring- Returns:
true
if the context menu was shown,false
otherwise
-
startActionMode
Start an action mode with the default typeActionMode.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
Start an action mode with the given type.- Parameters:
callback
- Callback that will control the lifecycle of the action modetype
- One ofActionMode.TYPE_PRIMARY
orActionMode.TYPE_FLOATING
.- Returns:
- The new action mode if it is started, null otherwise
- See Also:
-
createContextMenu
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 anView.OnCreateContextMenuListener
to add items to the context menu.- Parameters:
menu
- The context menu to populate
-
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 theView.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
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 theView
is in the state betweenonStartTemporaryDetach()
andonFinishTemporaryDetach()
.This method always returns
true
when called directly or indirectly fromonStartTemporaryDetach()
. The return value when called directly or indirectly fromonFinishTemporaryDetach()
.- Returns:
true
when the View is in the state betweenonStartTemporaryDetach()
andonFinishTemporaryDetach()
.
-
dispatchStartTemporaryDetach
DispatchonStartTemporaryDetach()
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, withViewGroup.detachViewFromParent(View)
. It will either be followed byonFinishTemporaryDetach()
oronDetachedFromWindow()
when the container is done. -
dispatchFinishTemporaryDetach
DispatchonFinishTemporaryDetach()
to this View and its direct children if this is a container View. -
onFinishTemporaryDetach
public void onFinishTemporaryDetach()Called afteronStartTemporaryDetach()
when the container is done changing the view. -
getKeyDispatcherState
Return the globalKeyEvent.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 likeonKeyDown(int, KeyEvent)
. -
dispatchKeyEvent
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
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
Default implementation: perform press of the view whenKeyEvent.KEY_ENTER
,KeyEvent.KEY_KP_ENTER
orKeyEvent.KEY_SPACE
is released, if the view is enabled and clickable.- Parameters:
keyCode
- a key code that represents the button pressed, fromKeyEvent
event
- the KeyEvent object that defines the button action
-
onKeyUp
Default implementation: perform clicking of the view whenKeyEvent.KEY_ENTER
,KeyEvent.KEY_KP_ENTER
orKeyEvent.KEY_SPACE
is released.- Parameters:
keyCode
- A key code that represents the button pressed, fromKeyEvent
.event
- The KeyEvent object that defines the button action.
-
onKeyShortcut
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 theshortcut
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
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
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
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
-
getLocalVisibleRect
-
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
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
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
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
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 callsetTooltipText(CharSequence)
to modify the tooltip text.- Returns:
- the tooltip text
- See Also:
-
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 asTransition
, where visibility changes should not adjust focus or trigger a new layout. Application developers should usesetVisibility(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. -
setTransitionName
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
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
-