Match the primary value activity on the left with its correct definition on the right.

  • Platform
  • Android Studio
  • Google Play
  • Jetpack
  • Kotlin
  • Docs
    • Overview
    • Guides
    • Reference
    • Samples
    • Design & Quality
  • Games

Show
Stay organized with collections Save and categorize content based on your preferences.

public class TextView
extends View implements ViewTreeObserver.OnPreDrawListener

Known indirect subclasses

AutoCompleteTextView

An editable text view that shows completion suggestions automatically while the user is typing. 

CheckBox

A checkbox is a specific type of two-states button that can be either checked or unchecked. 

CompoundButton

A button with two states, checked and unchecked. 

ExtractEditText Specialization of EditText for showing and interacting with the extracted text in a full-screen input method. 
MultiAutoCompleteTextView An editable text view, extending AutoCompleteTextView, that can show completion suggestions for the substring of the text where the user is typing instead of necessarily for the entire thing. 
RadioButton

A radio button is a two-states button that can be either checked or unchecked. 

Switch A Switch is a two-state toggle widget. 
ToggleButton Displays checked/unchecked states as a button with a "light" indicator and by default accompanied with the text "ON" or "OFF". 



A user interface element that displays text to the user. To provide user-editable text, see EditText.

The following code sample shows a typical use, with an XML layout and code to modify the contents of the text view:

 <LinearLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent">
    <TextView
        android:id="@+id/text_view_id"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/hello" />
 </LinearLayout>
 

This code sample demonstrates how to modify the contents of the text view defined in the previous XML layout:

 public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         final TextView helloTextView = (TextView) findViewById(R.id.text_view_id);
         helloTextView.setText(R.string.user_greeting);
     }
 }
 

To customize the appearance of TextView, see Styles and Themes.

XML attributes

See TextView Attributes, View Attributes

Summary

Nested classes

enum TextView.BufferType

Type of the text buffer that defines the characteristics of the text such as static, styleable, or editable. 

interface TextView.OnEditorActionListener

Interface definition for a callback to be invoked when an action is performed on the editor. 

class TextView.SavedState

User interface state that is stored by TextView for implementing View#onSaveInstanceState

XML attributes

android:allowUndo Whether undo should be allowed for editable text. 
android:autoLink Controls whether links such as urls and email addresses are automatically found and converted to clickable links. 
android:autoSizeMaxTextSize The maximum text size constraint to be used when auto-sizing text. 
android:autoSizeMinTextSize The minimum text size constraint to be used when auto-sizing text. 
android:autoSizePresetSizes Resource array of dimensions to be used in conjunction with autoSizeTextType set to uniform
android:autoSizeStepGranularity Specify the auto-size step size if autoSizeTextType is set to uniform
android:autoSizeTextType Specify the type of auto-size. 
android:autoText If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors. 
android:breakStrategy Break strategy (control over paragraph layout). 
android:bufferType Determines the minimum type that getText() will return. 
android:capitalize If set, specifies that this TextView has a textual input method and should automatically capitalize what the user types. 
android:cursorVisible Makes the cursor visible (the default) or invisible. 
android:digits If set, specifies that this TextView has a numeric input method and that these specific characters are the ones that it will accept. 
android:drawableBottom The drawable to be drawn below the text. 
android:drawableEnd The drawable to be drawn to the end of the text. 
android:drawableLeft The drawable to be drawn to the left of the text. 
android:drawablePadding The padding between the drawables and the text. 
android:drawableRight The drawable to be drawn to the right of the text. 
android:drawableStart The drawable to be drawn to the start of the text. 
android:drawableTint Tint to apply to the compound (left, top, etc.) drawables. 
android:drawableTintMode Blending mode used to apply the compound (left, top, etc.) drawables tint. 
android:drawableTop The drawable to be drawn above the text. 
android:editable If set, specifies that this TextView has an input method. 
android:editorExtras Reference to an <input-extras> XML resource containing additional data to supply to an input method, which is private to the implementation of the input method. 
android:elegantTextHeight Elegant text height, especially for less compacted complex script text. 
android:ellipsize If set, causes words that are longer than the view is wide to be ellipsized instead of broken in the middle. 
android:ems Makes the TextView be exactly this many ems wide. 
android:enabled Specifies whether the widget is enabled. 
android:fallbackLineSpacing Whether to respect the ascent and descent of the fallback fonts that are used in displaying the text. 
android:firstBaselineToTopHeight Distance from the top of the TextView to the first text baseline. 
android:fontFamily Font family (named by string or as a font resource reference) for the text. 
android:fontFeatureSettings Font feature settings. 
android:fontVariationSettings Font variation settings. 
android:freezesText If set, the text view will include its current complete text inside of its frozen icicle in addition to meta-data such as the current cursor position. 
android:gravity Specifies how to align the text by the view's x- and/or y-axis when the text is smaller than the view. 
android:height Makes the TextView be exactly this tall. 
android:hint Hint text to display when the text is empty. 
android:hyphenationFrequency Frequency of automatic hyphenation. 
android:imeActionId Supply a value for EditorInfo.actionId used when an input method is connected to the text view. 
android:imeActionLabel Supply a value for EditorInfo.actionLabel used when an input method is connected to the text view. 
android:imeOptions Additional features you can enable in an IME associated with an editor to improve the integration with your application. 
android:includeFontPadding Leave enough room for ascenders and descenders instead of using the font ascent and descent strictly. 
android:inputMethod If set, specifies that this TextView should use the specified input method (specified by fully-qualified class name). 
android:inputType The type of data being placed in a text field, used to help an input method decide how to let the user enter text. 
android:justificationMode Mode for justification. 
android:lastBaselineToBottomHeight Distance from the bottom of the TextView to the last text baseline. 
android:letterSpacing Text letter-spacing. 
android:lineBreakStyle Specifies the line-break strategies for text wrapping. 
android:lineBreakWordStyle Specifies the line-break word strategies for text wrapping. 
android:lineHeight Explicit height between lines of text. 
android:lineSpacingExtra Extra spacing between lines of text. 
android:lineSpacingMultiplier Extra spacing between lines of text, as a multiplier. 
android:lines Makes the TextView be exactly this many lines tall. 
android:linksClickable If set to false, keeps the movement method from being set to the link movement method even if autoLink causes links to be found. 
android:marqueeRepeatLimit The number of times to repeat the marquee animation. 
android:maxEms Makes the TextView be at most this many ems wide. 
android:maxHeight Makes the TextView be at most this many pixels tall. 
android:maxLength Set an input filter to constrain the text length to the specified number. 
android:maxLines Makes the TextView be at most this many lines tall. 
android:maxWidth Makes the TextView be at most this many pixels wide. 
android:minEms Makes the TextView be at least this many ems wide. 
android:minHeight Makes the TextView be at least this many pixels tall. 
android:minLines Makes the TextView be at least this many lines tall. 
android:minWidth Makes the TextView be at least this many pixels wide. 
android:numeric If set, specifies that this TextView has a numeric input method. 
android:password Whether the characters of the field are displayed as password dots instead of themselves. 
android:phoneNumber If set, specifies that this TextView has a phone number input method. 
android:privateImeOptions An addition content type description to supply to the input method attached to the text view, which is private to the implementation of the input method. 
android:scrollHorizontally Whether the text is allowed to be wider than the view (and therefore can be scrolled horizontally). 
android:selectAllOnFocus If the text is selectable, select it all when the view takes focus. 
android:shadowColor Place a blurred shadow of text underneath the text, drawn with the specified color. 
android:shadowDx Horizontal offset of the text shadow. 
android:shadowDy Vertical offset of the text shadow. 
android:shadowRadius Blur radius of the text shadow. 
android:singleLine Constrains the text to a single horizontally scrolling line instead of letting it wrap onto multiple lines, and advances focus instead of inserting a newline when you press the enter key. 
android:text Text to display. 
android:textAllCaps Present the text in ALL CAPS. 
android:textAppearance Base text color, typeface, size, and style. 
android:textColor Text color. 
android:textColorHighlight Color of the text selection highlight. 
android:textColorHint Color of the hint text. 
android:textColorLink Text color for links. 
android:textCursorDrawable Reference to a drawable that will be drawn under the insertion cursor. 
android:textFontWeight Weight for the font used in the TextView. 
android:textIsSelectable Indicates that the content of a non-editable text can be selected. 
android:textScaleX Sets the horizontal scaling factor for the text. 
android:textSelectHandle Reference to a drawable that will be used to display a text selection anchor for positioning the cursor within text. 
android:textSelectHandleLeft Reference to a drawable that will be used to display a text selection anchor on the left side of a selection region. 
android:textSelectHandleRight Reference to a drawable that will be used to display a text selection anchor on the right side of a selection region. 
android:textSize Size of the text. 
android:textStyle Style (normal, bold, italic, bold|italic) for the text. 
android:typeface Typeface (normal, sans, serif, monospace) for the text. 
android:width Makes the TextView be exactly this wide. 

Inherited XML attributes

From class android.view.View

android:accessibilityHeading Whether or not this view is a heading for accessibility purposes. 
android:accessibilityLiveRegion Indicates to accessibility services whether the user should be notified when this view changes. 
android:accessibilityPaneTitle The title this view should present to accessibility as a pane title. 
android:accessibilityTraversalAfter Sets the id of a view after which this one is visited in accessibility traversal. 
android:accessibilityTraversalBefore Sets the id of a view before which this one is visited in accessibility traversal. 
android:allowClickWhenDisabled Whether or not allow clicks on disabled view. 
android:alpha alpha property of the view, as a value between 0 (completely transparent) and 1 (completely opaque). 
android:autoHandwritingEnabled

Whether or not the auto handwriting initiation is enabled in this View. 

android:autofillHints Describes the content of a view so that a autofill service can fill in the appropriate data. 
android:autofilledHighlight Drawable to be drawn over the view to mark it as autofilled

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name". 

android:background A drawable to use as the background. 
android:backgroundTint Tint to apply to the background. 
android:backgroundTintMode Blending mode used to apply the background tint. 
android:clickable Defines whether this view reacts to click events. 
android:clipToOutline

Whether the View's Outline should be used to clip the contents of the View. 

android:contentDescription Defines text that briefly describes content of the view. 
android:contextClickable Defines whether this view reacts to context click events. 
android:defaultFocusHighlightEnabled Whether this View should use a default focus highlight when it gets focused but doesn't have R.attr.state_focused defined in its background. 
android:drawingCacheQuality Defines the quality of translucent drawing caches. 
android:duplicateParentState When this attribute is set to true, the view gets its drawable state (focused, pressed, etc.) from its direct parent rather than from itself. 
android:elevation base z depth of the view. 
android:fadeScrollbars Defines whether to fade out scrollbars when they are not in use. 
android:fadingEdgeLength Defines the length of the fading edges. 
android:filterTouchesWhenObscured Specifies whether to filter touches when the view's window is obscured by another visible window. 
android:fitsSystemWindows Boolean internal attribute to adjust view layout based on system windows such as the status bar. 
android:focusable Controls whether a view can take focus. 
android:focusableInTouchMode Boolean that controls whether a view can take focus while in touch mode. 
android:focusedByDefault Whether this view is a default-focus view. 
android:forceHasOverlappingRendering Whether this view has elements that may overlap when drawn. 
android:foreground Defines the drawable to draw over the content. 
android:foregroundGravity Defines the gravity to apply to the foreground drawable. 
android:foregroundTint Tint to apply to the foreground. 
android:foregroundTintMode Blending mode used to apply the foreground tint. 
android:hapticFeedbackEnabled Boolean that controls whether a view should have haptic feedback enabled for events such as long presses. 
android:id Supply an identifier name for this view, to later retrieve it with View.findViewById() or Activity.findViewById()
android:importantForAccessibility Describes whether or not this view is important for accessibility. 
android:importantForAutofill Hints the Android System whether the view node associated with this View should be included in a view structure used for autofill purposes. 
android:importantForContentCapture Hints the Android System whether the view node associated with this View should be use for content capture purposes. 
android:isScrollContainer Set this if the view will serve as a scrolling container, meaning that it can be resized to shrink its overall window so that there will be space for an input method. 
android:keepScreenOn Controls whether the view's window should keep the screen on while visible. 
android:keyboardNavigationCluster Whether this view is a root of a keyboard navigation cluster. 
android:layerType Specifies the type of layer backing this view. 
android:layoutDirection Defines the direction of layout drawing. 
android:longClickable Defines whether this view reacts to long click events. 
android:minHeight Defines the minimum height of the view. 
android:minWidth Defines the minimum width of the view. 
android:nextClusterForward Defines the next keyboard navigation cluster. 
android:nextFocusDown Defines the next view to give focus to when the next focus is View.FOCUS_DOWN If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a RuntimeException will result when the reference is accessed. 
android:nextFocusForward Defines the next view to give focus to when the next focus is View.FOCUS_FORWARD If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a RuntimeException will result when the reference is accessed. 
android:nextFocusLeft Defines the next view to give focus to when the next focus is View.FOCUS_LEFT
android:nextFocusRight Defines the next view to give focus to when the next focus is View.FOCUS_RIGHT If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a RuntimeException will result when the reference is accessed. 
android:nextFocusUp Defines the next view to give focus to when the next focus is View.FOCUS_UP If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a RuntimeException will result when the reference is accessed. 
android:onClick Name of the method in this View's context to invoke when the view is clicked. 
android:outlineAmbientShadowColor Sets the color of the ambient shadow that is drawn when the view has a positive Z or elevation value. 
android:outlineSpotShadowColor Sets the color of the spot shadow that is drawn when the view has a positive Z or elevation value. 
android:padding Sets the padding, in pixels, of all four edges. 
android:paddingBottom Sets the padding, in pixels, of the bottom edge; see R.attr.padding
android:paddingEnd Sets the padding, in pixels, of the end edge; see R.attr.padding
android:paddingHorizontal Sets the padding, in pixels, of the left and right edges; see R.attr.padding
android:paddingLeft Sets the padding, in pixels, of the left edge; see R.attr.padding
android:paddingRight Sets the padding, in pixels, of the right edge; see R.attr.padding
android:paddingStart Sets the padding, in pixels, of the start edge; see R.attr.padding
android:paddingTop Sets the padding, in pixels, of the top edge; see R.attr.padding
android:paddingVertical Sets the padding, in pixels, of the top and bottom edges; see R.attr.padding
android:preferKeepClear

Sets a preference to keep the bounds of this view clear from floating windows above this view's window. 

android:requiresFadingEdge Defines which edges should be faded on scrolling. 
android:rotation rotation of the view, in degrees. 
android:rotationX rotation of the view around the x axis, in degrees. 
android:rotationY rotation of the view around the y axis, in degrees. 
android:saveEnabled If false, no state will be saved for this view when it is being frozen. 
android:scaleX scale of the view in the x direction. 
android:scaleY scale of the view in the y direction. 
android:screenReaderFocusable Whether this view should be treated as a focusable unit by screen reader accessibility tools. 
android:scrollIndicators Defines which scroll indicators should be displayed when the view can be scrolled. 
android:scrollX The initial horizontal scroll offset, in pixels. 
android:scrollY The initial vertical scroll offset, in pixels. 
android:scrollbarAlwaysDrawHorizontalTrack Defines whether the horizontal scrollbar track should always be drawn. 
android:scrollbarAlwaysDrawVerticalTrack Defines whether the vertical scrollbar track should always be drawn. 
android:scrollbarDefaultDelayBeforeFade Defines the delay in milliseconds that a scrollbar waits before fade out. 
android:scrollbarFadeDuration Defines the delay in milliseconds that a scrollbar takes to fade out. 
android:scrollbarSize Sets the width of vertical scrollbars and height of horizontal scrollbars. 
android:scrollbarStyle Controls the scrollbar style and position. 
android:scrollbarThumbHorizontal Defines the horizontal scrollbar thumb drawable. 
android:scrollbarThumbVertical Defines the vertical scrollbar thumb drawable. 
android:scrollbarTrackHorizontal Defines the horizontal scrollbar track drawable. 
android:scrollbarTrackVertical Defines the vertical scrollbar track drawable. 
android:scrollbars Defines which scrollbars should be displayed on scrolling or not. 
android:soundEffectsEnabled Boolean that controls whether a view should have sound effects enabled for events such as clicking and touching. 
android:stateListAnimator Sets the state-based animator for the View. 
android:tag Supply a tag for this view containing a String, to be retrieved later with View.getTag() or searched for with View.findViewWithTag()
android:textAlignment Defines the alignment of the text. 
android:textDirection Defines the direction of the text. 
android:theme Specifies a theme override for a view. 
android:tooltipText Defines text displayed in a small popup window on hover or long press. 
android:transformPivotX x location of the pivot point around which the view will rotate and scale. 
android:transformPivotY y location of the pivot point around which the view will rotate and scale. 
android:transitionName Names a View such that it can be identified for Transitions. 
android:translationX translation in x of the view. 
android:translationY translation in y of the view. 
android:translationZ translation in z of the view. 
android:visibility Controls the initial visibility of the view. 

Constants

int AUTO_SIZE_TEXT_TYPE_NONE

The TextView does not auto-size text (default).

int AUTO_SIZE_TEXT_TYPE_UNIFORM

The TextView scales text size both horizontally and vertically to fit within the container.

Inherited constants

From class android.view.View

int ACCESSIBILITY_LIVE_REGION_ASSERTIVE

Live region mode specifying that accessibility services should interrupt ongoing speech to immediately announce changes to this view.

int ACCESSIBILITY_LIVE_REGION_NONE

Live region mode specifying that accessibility services should not automatically announce changes to this view.

int ACCESSIBILITY_LIVE_REGION_POLITE

Live region mode specifying that accessibility services should announce changes to this view.

int AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS

Flag requesting you to add views that are marked as not important for autofill (see setImportantForAutofill(int)) to a ViewStructure.

String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE

Hint indicating that this view can be autofilled with a credit card expiration date.

String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY

Hint indicating that this view can be autofilled with a credit card expiration day.

String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH

Hint indicating that this view can be autofilled with a credit card expiration month.

String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR

Hint indicating that this view can be autofilled with a credit card expiration year.

String AUTOFILL_HINT_CREDIT_CARD_NUMBER

Hint indicating that this view can be autofilled with a credit card number.

String AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE

Hint indicating that this view can be autofilled with a credit card security code.

String AUTOFILL_HINT_EMAIL_ADDRESS

Hint indicating that this view can be autofilled with an email address.

String AUTOFILL_HINT_NAME

Hint indicating that this view can be autofilled with a user's real name.

String AUTOFILL_HINT_PASSWORD

Hint indicating that this view can be autofilled with a password.

String AUTOFILL_HINT_PHONE

Hint indicating that this view can be autofilled with a phone number.

String AUTOFILL_HINT_POSTAL_ADDRESS

Hint indicating that this view can be autofilled with a postal address.

String AUTOFILL_HINT_POSTAL_CODE

Hint indicating that this view can be autofilled with a postal code.

String AUTOFILL_HINT_USERNAME

Hint indicating that this view can be autofilled with a username.

int AUTOFILL_TYPE_DATE

Autofill type for a field that contains a date, which is represented by a long representing the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (see Date.getTime().

int AUTOFILL_TYPE_LIST

Autofill type for a selection list field, which is filled by an int representing the element index inside the list (starting at 0).

int AUTOFILL_TYPE_NONE

Autofill type for views that cannot be autofilled.

int AUTOFILL_TYPE_TEXT

Autofill type for a text field, which is filled by a CharSequence.

int AUTOFILL_TYPE_TOGGLE

Autofill type for a togglable field, which is filled by a boolean.

int DRAG_FLAG_ACCESSIBILITY_ACTION

Flag indicating that the drag was initiated with AccessibilityNodeInfo.AccessibilityAction#ACTION_DRAG_START.

int DRAG_FLAG_GLOBAL

Flag indicating that a drag can cross window boundaries.

int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION

When this flag is used with DRAG_FLAG_GLOBAL_URI_READ and/or DRAG_FLAG_GLOBAL_URI_WRITE, the URI permission grant can be persisted across device reboots until explicitly revoked with Context.revokeUriPermission(Uri, int) Context.revokeUriPermission}.

int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION

When this flag is used with DRAG_FLAG_GLOBAL_URI_READ and/or DRAG_FLAG_GLOBAL_URI_WRITE, the URI permission grant applies to any URI that is a prefix match against the original granted URI.

int DRAG_FLAG_GLOBAL_URI_READ

When this flag is used with DRAG_FLAG_GLOBAL, the drag recipient will be able to request read access to the content URI(s) contained in the ClipData object.

int DRAG_FLAG_GLOBAL_URI_WRITE

When this flag is used with DRAG_FLAG_GLOBAL, the drag recipient will be able to request write access to the content URI(s) contained in the ClipData object.

int DRAG_FLAG_OPAQUE

Flag indicating that the drag shadow will be opaque.

int DRAWING_CACHE_QUALITY_AUTO

This constant was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

int DRAWING_CACHE_QUALITY_HIGH

This constant was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

int DRAWING_CACHE_QUALITY_LOW

This constant was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

int FIND_VIEWS_WITH_CONTENT_DESCRIPTION

Find find views that contain the specified content description.

int FIND_VIEWS_WITH_TEXT

Find views that render the specified text.

int FOCUSABLE

This view wants keystrokes.

int FOCUSABLES_ALL

View flag indicating whether addFocusables(java.util.ArrayList, int, int) should add all focusable Views regardless if they are focusable in touch mode.

int FOCUSABLES_TOUCH_MODE

View flag indicating whether addFocusables(java.util.ArrayList, int, int) should add only Views focusable in touch mode.

int FOCUSABLE_AUTO

This view determines focusability automatically.

int FOCUS_BACKWARD

Use with focusSearch(int).

int FOCUS_DOWN

Use with focusSearch(int).

int FOCUS_FORWARD

Use with focusSearch(int).

int FOCUS_LEFT

Use with focusSearch(int).

int FOCUS_RIGHT

Use with focusSearch(int).

int FOCUS_UP

Use with focusSearch(int).

int GONE

This view is invisible, and it doesn't take any space for layout purposes.

int HAPTIC_FEEDBACK_ENABLED

View flag indicating whether this view should have haptic feedback enabled for events such as long presses.

int IMPORTANT_FOR_ACCESSIBILITY_AUTO

Automatically determine whether a view is important for accessibility.

int IMPORTANT_FOR_ACCESSIBILITY_NO

The view is not important for accessibility.

int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS

The view is not important for accessibility, nor are any of its descendant views.

int IMPORTANT_FOR_ACCESSIBILITY_YES

The view is important for accessibility.

int IMPORTANT_FOR_AUTOFILL_AUTO

Automatically determine whether a view is important for autofill.

int IMPORTANT_FOR_AUTOFILL_NO

The view is not important for autofill, but its children (if any) will be traversed.

int IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS

The view is not important for autofill, and its children (if any) will not be traversed.

int IMPORTANT_FOR_AUTOFILL_YES

The view is important for autofill, and its children (if any) will be traversed.

int IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS

The view is important for autofill, but its children (if any) will not be traversed.

int IMPORTANT_FOR_CONTENT_CAPTURE_AUTO

Automatically determine whether a view is important for content capture.

int IMPORTANT_FOR_CONTENT_CAPTURE_NO

The view is not important for content capture, but its children (if any) will be traversed.

int IMPORTANT_FOR_CONTENT_CAPTURE_NO_EXCLUDE_DESCENDANTS

The view is not important for content capture, and its children (if any) will not be traversed.

int IMPORTANT_FOR_CONTENT_CAPTURE_YES

The view is important for content capture, and its children (if any) will be traversed.

int IMPORTANT_FOR_CONTENT_CAPTURE_YES_EXCLUDE_DESCENDANTS

The view is important for content capture, but its children (if any) will not be traversed.

int INVISIBLE

This view is invisible, but it still takes up space for layout purposes.

int KEEP_SCREEN_ON

View flag indicating that the screen should remain on while the window containing this view is visible to the user.

int LAYER_TYPE_HARDWARE

Indicates that the view has a hardware layer.

int LAYER_TYPE_NONE

Indicates that the view does not have a layer.

int LAYER_TYPE_SOFTWARE

Indicates that the view has a software layer.

int LAYOUT_DIRECTION_INHERIT

Horizontal layout direction of this view is inherited from its parent.

int LAYOUT_DIRECTION_LOCALE

Horizontal layout direction of this view is from deduced from the default language script for the locale.

int LAYOUT_DIRECTION_LTR

Horizontal layout direction of this view is from Left to Right.

int LAYOUT_DIRECTION_RTL

Horizontal layout direction of this view is from Right to Left.

int MEASURED_HEIGHT_STATE_SHIFT

Bit shift of MEASURED_STATE_MASK to get to the height bits for functions that combine both width and height into a single int, such as getMeasuredState() and the childState argument of resolveSizeAndState(int, int, int).

int MEASURED_SIZE_MASK

Bits of getMeasuredWidthAndState() and getMeasuredWidthAndState() that provide the actual measured size.

int MEASURED_STATE_MASK

Bits of getMeasuredWidthAndState() and getMeasuredWidthAndState() that provide the additional state bits.

int MEASURED_STATE_TOO_SMALL

Bit of getMeasuredWidthAndState() and getMeasuredWidthAndState() that indicates the measured size is smaller that the space the view would like to have.

int NOT_FOCUSABLE

This view does not want keystrokes.

int NO_ID

Used to mark a View that has no ID.

int OVER_SCROLL_ALWAYS

Always allow a user to over-scroll this view, provided it is a view that can scroll.

int OVER_SCROLL_IF_CONTENT_SCROLLS

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.

int OVER_SCROLL_NEVER

Never allow a user to over-scroll this view.

int SCREEN_STATE_OFF

Indicates that the screen has changed state and is now off.

int SCREEN_STATE_ON

Indicates that the screen has changed state and is now on.

int SCROLLBARS_INSIDE_INSET

The scrollbar style to display the scrollbars inside the padded area, increasing the padding of the view.

int SCROLLBARS_INSIDE_OVERLAY

The scrollbar style to display the scrollbars inside the content area, without increasing the padding.

int SCROLLBARS_OUTSIDE_INSET

The scrollbar style to display the scrollbars at the edge of the view, increasing the padding of the view.

int SCROLLBARS_OUTSIDE_OVERLAY

The scrollbar style to display the scrollbars at the edge of the view, without increasing the padding.

int SCROLLBAR_POSITION_DEFAULT

Position the scroll bar at the default position as determined by the system.

int SCROLLBAR_POSITION_LEFT

Position the scroll bar along the left edge.

int SCROLLBAR_POSITION_RIGHT

Position the scroll bar along the right edge.

int SCROLL_AXIS_HORIZONTAL

Indicates scrolling along the horizontal axis.

int SCROLL_AXIS_NONE

Indicates no axis of view scrolling.

int SCROLL_AXIS_VERTICAL

Indicates scrolling along the vertical axis.

int SCROLL_CAPTURE_HINT_AUTO

The content of this view will be considered for scroll capture if scrolling is possible.

int SCROLL_CAPTURE_HINT_EXCLUDE

Explicitly exclude this view as a potential scroll capture target.

int SCROLL_CAPTURE_HINT_EXCLUDE_DESCENDANTS

Explicitly exclude all children of this view as potential scroll capture targets.

int SCROLL_CAPTURE_HINT_INCLUDE

Explicitly include this view as a potential scroll capture target.

int SCROLL_INDICATOR_BOTTOM

Scroll indicator direction for the bottom edge of the view.

int SCROLL_INDICATOR_END

Scroll indicator direction for the ending edge of the view.

int SCROLL_INDICATOR_LEFT

Scroll indicator direction for the left edge of the view.

int SCROLL_INDICATOR_RIGHT

Scroll indicator direction for the right edge of the view.

int SCROLL_INDICATOR_START

Scroll indicator direction for the starting edge of the view.

int SCROLL_INDICATOR_TOP

Scroll indicator direction for the top edge of the view.

int SOUND_EFFECTS_ENABLED

View flag indicating whether this view should have sound effects enabled for events such as clicking and touching.

int STATUS_BAR_HIDDEN

This constant was deprecated in API level 15. Use SYSTEM_UI_FLAG_LOW_PROFILE instead.

int STATUS_BAR_VISIBLE

This constant was deprecated in API level 15. Use SYSTEM_UI_FLAG_VISIBLE instead.

int SYSTEM_UI_FLAG_FULLSCREEN

This constant was deprecated in API level 30. Use WindowInsetsController#hide(int) with Type#statusBars() instead.

int SYSTEM_UI_FLAG_HIDE_NAVIGATION

This constant was deprecated in API level 30. Use WindowInsetsController#hide(int) with Type#navigationBars() instead.

int SYSTEM_UI_FLAG_IMMERSIVE

This constant was deprecated in API level 30. Use WindowInsetsController#BEHAVIOR_DEFAULT instead.

int SYSTEM_UI_FLAG_IMMERSIVE_STICKY

This constant was deprecated in API level 30. Use WindowInsetsController#BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE instead.

int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

This constant was deprecated in API level 30. For floating windows, use LayoutParams#setFitInsetsTypes(int) with Type#statusBars() ()}. For non-floating windows that fill the screen, call Window#setDecorFitsSystemWindows(boolean) with false.

int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION

This constant was deprecated in API level 30. For floating windows, use LayoutParams#setFitInsetsTypes(int) with Type#navigationBars(). For non-floating windows that fill the screen, call Window#setDecorFitsSystemWindows(boolean) with false.

int SYSTEM_UI_FLAG_LAYOUT_STABLE

This constant was deprecated in API level 30. Use WindowInsets#getInsetsIgnoringVisibility(int) instead to retrieve insets that don't change when system bars change visibility state.

int SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR

This constant was deprecated in API level 30. Use WindowInsetsController#APPEARANCE_LIGHT_NAVIGATION_BARS instead.

int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR

This constant was deprecated in API level 30. Use WindowInsetsController#APPEARANCE_LIGHT_STATUS_BARS instead.

int SYSTEM_UI_FLAG_LOW_PROFILE

This constant was deprecated in API level 30. Low profile mode is deprecated. Hide the system bars instead if the application needs to be in a unobtrusive mode. Use WindowInsetsController#hide(int) with Type#systemBars().

int SYSTEM_UI_FLAG_VISIBLE

This constant was deprecated in API level 30. SystemUiVisibility flags are deprecated. Use WindowInsetsController instead.

int SYSTEM_UI_LAYOUT_FLAGS

This constant was deprecated in API level 30. System UI layout flags are deprecated.

int TEXT_ALIGNMENT_CENTER

Center the paragraph, e.g. ALIGN_CENTER.

int TEXT_ALIGNMENT_GRAVITY

Default for the root view.

int TEXT_ALIGNMENT_INHERIT

Default text alignment.

int TEXT_ALIGNMENT_TEXT_END

Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.

int TEXT_ALIGNMENT_TEXT_START

Align to the start of the paragraph, e.g. ALIGN_NORMAL.

int TEXT_ALIGNMENT_VIEW_END

Align to the end of the view, which is ALIGN_RIGHT if the view's resolved layoutDirection is LTR, and ALIGN_LEFT otherwise.

int TEXT_ALIGNMENT_VIEW_START

Align to the start of the view, which is ALIGN_LEFT if the view's resolved layoutDirection is LTR, and ALIGN_RIGHT otherwise.

int TEXT_DIRECTION_ANY_RTL

Text direction is using "any-RTL" algorithm.

int TEXT_DIRECTION_FIRST_STRONG

Text direction is using "first strong algorithm".

int TEXT_DIRECTION_FIRST_STRONG_LTR

Text direction is using "first strong algorithm".

int TEXT_DIRECTION_FIRST_STRONG_RTL

Text direction is using "first strong algorithm".

int TEXT_DIRECTION_INHERIT

Text direction is inherited through ViewGroup

int TEXT_DIRECTION_LOCALE

Text direction is coming from the system Locale.

int TEXT_DIRECTION_LTR

Text direction is forced to LTR.

int TEXT_DIRECTION_RTL

Text direction is forced to RTL.

String VIEW_LOG_TAG

The logging tag used by this class with android.util.Log.

int VISIBLE

This view is visible.

Inherited fields

From class android.view.View

public static final Property<View, Float> ALPHA

A Property wrapper around the alpha functionality handled by the View#setAlpha(float) and View#getAlpha() methods.

protected static final int[] EMPTY_STATE_SET

Indicates the view has no states set.

protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET

Indicates the view is enabled, focused and selected.

protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET

Indicates the view is enabled, focused, selected and its window has the focus.

protected static final int[] ENABLED_FOCUSED_STATE_SET

Indicates the view is enabled and has the focus.

protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET

Indicates the view is enabled, focused and its window has the focus.

protected static final int[] ENABLED_SELECTED_STATE_SET

Indicates the view is enabled and selected.

protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET

Indicates the view is enabled, selected and its window has the focus.

protected static final int[] ENABLED_STATE_SET

Indicates the view is enabled.

protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET

Indicates the view is enabled and that its window has focus.

protected static final int[] FOCUSED_SELECTED_STATE_SET

Indicates the view is focused and selected.

protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET

Indicates the view is focused, selected and its window has the focus.

protected static final int[] FOCUSED_STATE_SET

Indicates the view is focused.

protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET

Indicates the view has the focus and that its window has the focus.

protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET

Indicates the view is pressed, enabled, focused and selected.

protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET

Indicates the view is pressed, enabled, focused, selected and its window has the focus.

protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET

Indicates the view is pressed, enabled and focused.

protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET

Indicates the view is pressed, enabled, focused and its window has the focus.

protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET

Indicates the view is pressed, enabled and selected.

protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET

Indicates the view is pressed, enabled, selected and its window has the focus.

protected static final int[] PRESSED_ENABLED_STATE_SET

Indicates the view is pressed and enabled.

protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET

Indicates the view is pressed, enabled and its window has the focus.

protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET

Indicates the view is pressed, focused and selected.

protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET

Indicates the view is pressed, focused, selected and its window has the focus.

protected static final int[] PRESSED_FOCUSED_STATE_SET

Indicates the view is pressed and focused.

protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET

Indicates the view is pressed, focused and its window has the focus.

protected static final int[] PRESSED_SELECTED_STATE_SET

Indicates the view is pressed and selected.

protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET

Indicates the view is pressed, selected and its window has the focus.

protected static final int[] PRESSED_STATE_SET

Indicates the view is pressed.

protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET

Indicates the view is pressed and its window has the focus.

public static final Property<View, Float> ROTATION

A Property wrapper around the rotation functionality handled by the View#setRotation(float) and View#getRotation() methods.

public static final Property<View, Float> ROTATION_X

A Property wrapper around the rotationX functionality handled by the View#setRotationX(float) and View#getRotationX() methods.

public static final Property<View, Float> ROTATION_Y

A Property wrapper around the rotationY functionality handled by the View#setRotationY(float) and View#getRotationY() methods.

public static final Property<View, Float> SCALE_X

A Property wrapper around the scaleX functionality handled by the View#setScaleX(float) and View#getScaleX() methods.

public static final Property<View, Float> SCALE_Y

A Property wrapper around the scaleY functionality handled by the View#setScaleY(float) and View#getScaleY() methods.

protected static final int[] SELECTED_STATE_SET

Indicates the view is selected.

protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET

Indicates the view is selected and that its window has the focus.

public static final Property<View, Float> TRANSLATION_X

A Property wrapper around the translationX functionality handled by the View#setTranslationX(float) and View#getTranslationX() methods.

public static final Property<View, Float> TRANSLATION_Y

A Property wrapper around the translationY functionality handled by the View#setTranslationY(float) and View#getTranslationY() methods.

public static final Property<View, Float> TRANSLATION_Z

A Property wrapper around the translationZ functionality handled by the View#setTranslationZ(float) and View#getTranslationZ() methods.

protected static final int[] WINDOW_FOCUSED_STATE_SET

Indicates the view's window has focus.

public static final Property<View, Float> X

A Property wrapper around the x functionality handled by the View#setX(float) and View#getX() methods.

public static final Property<View, Float> Y

A Property wrapper around the y functionality handled by the View#setY(float) and View#getY() methods.

public static final Property<View, Float> Z

A Property wrapper around the z functionality handled by the View#setZ(float) and View#getZ() methods.

Public constructors

TextView(Context context)
TextView(Context context, AttributeSet attrs)
TextView(Context context, AttributeSet attrs, int defStyleAttr)
TextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)

Public methods

void addExtraDataToAccessibilityNodeInfo(AccessibilityNodeInfo info, String extraDataKey, Bundle arguments)

Adds extra data to an AccessibilityNodeInfo based on an explicit request for the additional data.

void addTextChangedListener(TextWatcher watcher)

Adds a TextWatcher to the list of those whose methods are called whenever this TextView's text changes.

final void append(CharSequence text)

Convenience method to append the specified text to the TextView's display buffer, upgrading it to TextView.BufferType.EDITABLE if it was not already editable.

void append(CharSequence text, int start, int end)

Convenience method to append the specified text slice to the TextView's display buffer, upgrading it to TextView.BufferType.EDITABLE if it was not already editable.

void autofill(AutofillValue value)

Automatically fills the content of this view with the value.

void beginBatchEdit()
boolean bringPointIntoView(int offset)

Move the point, specified by the offset, into the view if it is needed.

void cancelLongPress()

Cancels a pending long press.

void clearComposingText()

Use BaseInputConnection.removeComposingSpans() to remove any IME composing state from this text view.

void computeScroll()

Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary.

void debug(int depth)
boolean didTouchFocusSelect()

Returns true, only while processing a touch gesture, if the initial touch down event caused focus to move to the text view and as a result its selection changed.

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.

void endBatchEdit()
boolean extractText(ExtractedTextRequest request, ExtractedText outText)

If this TextView contains editable content, extract a portion of it based on the information in request in to outText.

void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags)

Finds the Views that contain given text.

CharSequence getAccessibilityClassName()

Return the class name of this object to be used for accessibility purposes.

final int getAutoLinkMask()

Gets the autolink mask of the text.

int getAutoSizeMaxTextSize()
int getAutoSizeMinTextSize()
int getAutoSizeStepGranularity()
int[] getAutoSizeTextAvailableSizes()
int getAutoSizeTextType()

Returns the type of auto-size set for this widget.

String[] getAutofillHints()

Gets the hints that help an AutofillService determine how to autofill the view with the user's data.

int getAutofillType()

Describes the autofill type of this view, so an AutofillService can create the proper AutofillValue when autofilling the view.

AutofillValue getAutofillValue()

Gets the TextView's current text for AutoFill.

int getBaseline()

Return the offset of the widget's text baseline from the widget's top boundary.

int getBreakStrategy()

Gets the current strategy for breaking paragraphs into lines.

int getCompoundDrawablePadding()

Returns the padding between the compound drawables and the text.

BlendMode getCompoundDrawableTintBlendMode()

Returns the blending mode used to apply the tint to the compound drawables, if specified.

ColorStateList getCompoundDrawableTintList()
PorterDuff.Mode getCompoundDrawableTintMode()

Returns the blending mode used to apply the tint to the compound drawables, if specified.

Drawable[] getCompoundDrawables()

Returns drawables for the left, top, right, and bottom borders.

Drawable[] getCompoundDrawablesRelative()

Returns drawables for the start, top, end, and bottom borders.

int getCompoundPaddingBottom()

Returns the bottom padding of the view, plus space for the bottom Drawable if any.

int getCompoundPaddingEnd()

Returns the end padding of the view, plus space for the end Drawable if any.

int getCompoundPaddingLeft()

Returns the left padding of the view, plus space for the left Drawable if any.

int getCompoundPaddingRight()

Returns the right padding of the view, plus space for the right Drawable if any.

int getCompoundPaddingStart()

Returns the start padding of the view, plus space for the start Drawable if any.

int getCompoundPaddingTop()

Returns the top padding of the view, plus space for the top Drawable if any.

final int getCurrentHintTextColor()

Return the current color selected to paint the hint text.

final int getCurrentTextColor()

Return the current color selected for normal text.

ActionMode.Callback getCustomInsertionActionModeCallback()

Retrieves the value set in setCustomInsertionActionModeCallback(ActionMode.Callback).

ActionMode.Callback getCustomSelectionActionModeCallback()

Retrieves the value set in setCustomSelectionActionModeCallback(ActionMode.Callback).

Editable getEditableText()

Return the text that TextView is displaying as an Editable object.

TextUtils.TruncateAt getEllipsize()

Returns where, if anywhere, words that are longer than the view is wide should be ellipsized.

CharSequence getError()

Returns the error message that was set to be displayed with setError(CharSequence), or null if no error was set or if it the error was cleared by the widget after user input.

int getExtendedPaddingBottom()

Returns the extended bottom padding of the view, including both the bottom Drawable if any and any extra space to keep more than maxLines of text from showing.

int getExtendedPaddingTop()

Returns the extended top padding of the view, including both the top Drawable if any and any extra space to keep more than maxLines of text from showing.

InputFilter[] getFilters()

Returns the current list of input filters.

int getFirstBaselineToTopHeight()

Returns the distance between the first text baseline and the top of this TextView.

void getFocusedRect(Rect r)

When a view has focus and the user navigates away from it, the next view is searched for starting from the rectangle filled in by this method.

String getFontFeatureSettings()

Returns the font feature settings.

String getFontVariationSettings()

Returns the font variation settings.

boolean getFreezesText()

Return whether this text view is including its entire text contents in frozen icicles.

int getGravity()

Returns the horizontal and vertical alignment of this TextView.

int getHighlightColor()
CharSequence getHint()

Returns the hint that is displayed when the text of the TextView is empty.

final ColorStateList getHintTextColors()
int getHyphenationFrequency()

Gets the current frequency of automatic hyphenation to be used when determining word breaks.

int getImeActionId()

Get the IME action ID previous set with setImeActionLabel(CharSequence, int).

CharSequence getImeActionLabel()

Get the IME action label previous set with setImeActionLabel(CharSequence, int).

LocaleList getImeHintLocales()
int getImeOptions()

Get the type of the Input Method Editor (IME).

boolean getIncludeFontPadding()

Gets whether the TextView includes extra top and bottom padding to make room for accents that go above the normal ascent and descent.

Bundle getInputExtras(boolean create)

Retrieve the input extras currently associated with the text view, which can be viewed as well as modified.

int getInputType()

Get the type of the editable content.

int getJustificationMode()
final KeyListener getKeyListener()

Gets the current KeyListener for the TextView.

int getLastBaselineToBottomHeight()

Returns the distance between the last text baseline and the bottom of this TextView.

final Layout getLayout()

Gets the Layout that is currently being used to display the text.

float getLetterSpacing()

Gets the text letter-space value, which determines the spacing between characters.

int getLineBounds(int line, Rect bounds)

Return the baseline for the specified line (0...getLineCount() - 1) If bounds is not null, return the top, left, right, bottom extents of the specified line in it.

int getLineBreakStyle()

Gets the current line-break style for text wrapping.

int getLineBreakWordStyle()

Gets the current line-break word style for text wrapping.

int getLineCount()

Return the number of lines of text, or 0 if the internal Layout has not been built.

int getLineHeight()

Gets the vertical distance between lines of text, in pixels.

float getLineSpacingExtra()

Gets the line spacing extra space

float getLineSpacingMultiplier()

Gets the line spacing multiplier

final ColorStateList getLinkTextColors()
final boolean getLinksClickable()

Returns whether the movement method will automatically be set to LinkMovementMethod if setAutoLinkMask(int) has been set to nonzero and links are detected in setText(char[], int, int).

int getMarqueeRepeatLimit()

Gets the number of times the marquee animation is repeated.

int getMaxEms()

Returns the maximum width of TextView in terms of ems or -1 if the maximum width was set using setMaxWidth(int) or setWidth(int).

int getMaxHeight()

Returns the maximum height of TextView in terms of pixels or -1 if the maximum height was set using setMaxLines(int) or setLines(int).

int getMaxLines()

Returns the maximum height of TextView in terms of number of lines or -1 if the maximum height was set using setMaxHeight(int) or setHeight(int).

int getMaxWidth()

Returns the maximum width of TextView in terms of pixels or -1 if the maximum width was set using setMaxEms(int) or setEms(int).

int getMinEms()

Returns the minimum width of TextView in terms of ems or -1 if the minimum width was set using setMinWidth(int) or setWidth(int).

int getMinHeight()

Returns the minimum height of TextView in terms of pixels or -1 if the minimum height was set using setMinLines(int) or setLines(int).

int getMinLines()

Returns the minimum height of TextView in terms of number of lines or -1 if the minimum height was set using setMinHeight(int) or setHeight(int).

int getMinWidth()

Returns the minimum width of TextView in terms of pixels or -1 if the minimum width was set using setMinEms(int) or setEms(int).

final MovementMethod getMovementMethod()

Gets the MovementMethod being used for this TextView, which provides positioning, scrolling, and text selection functionality.

int getOffsetForPosition(float x, float y)

Get the character offset closest to the specified absolute position.

TextPaint getPaint()

Gets the TextPaint used for the text.

int getPaintFlags()

Gets the flags on the Paint being used to display the text.

String getPrivateImeOptions()

Get the private type of the content.

int getSelectionEnd()

Convenience for Selection#getSelectionEnd.

int getSelectionStart()

Convenience for Selection#getSelectionStart.

int getShadowColor()

Gets the color of the shadow layer.

float getShadowDx()
float getShadowDy()

Gets the vertical offset of the shadow layer.

float getShadowRadius()

Gets the radius of the shadow layer.

final boolean getShowSoftInputOnFocus()

Returns whether the soft input method will be made visible when this TextView gets focused.

CharSequence getText()

Return the text that TextView is displaying.

TextClassifier getTextClassifier()

Returns the TextClassifier used by this TextView.

final ColorStateList getTextColors()

Gets the text colors for the different states (normal, selected, focused) of the TextView.

Drawable getTextCursorDrawable()

Returns the Drawable corresponding to the text cursor.

TextDirectionHeuristic getTextDirectionHeuristic()

Returns resolved TextDirectionHeuristic that will be used for text layout.

Locale getTextLocale()

Get the default primary Locale of the text in this TextView.

LocaleList getTextLocales()

Get the default LocaleList of the text in this TextView.

PrecomputedText.Params getTextMetricsParams()

Gets the parameters for text layout precomputation, for use with PrecomputedText.

float getTextScaleX()

Gets the extent by which text should be stretched horizontally.

Drawable getTextSelectHandle()

Returns the Drawable corresponding to the selection handle used for positioning the cursor within text.

Drawable getTextSelectHandleLeft()

Returns the Drawable corresponding to the left handle used for selecting text.

Drawable getTextSelectHandleRight()

Returns the Drawable corresponding to the right handle used for selecting text.

float getTextSize()
int getTextSizeUnit()

Gets the text size unit defined by the developer.

int getTotalPaddingBottom()

Returns the total bottom padding of the view, including the bottom Drawable if any, the extra space to keep more than maxLines from showing, and the vertical offset for gravity, if any.

int getTotalPaddingEnd()

Returns the total end padding of the view, including the end Drawable if any.

int getTotalPaddingLeft()

Returns the total left padding of the view, including the left Drawable if any.

int getTotalPaddingRight()

Returns the total right padding of the view, including the right Drawable if any.

int getTotalPaddingStart()

Returns the total start padding of the view, including the start Drawable if any.

int getTotalPaddingTop()

Returns the total top padding of the view, including the top Drawable if any, the extra space to keep more than maxLines from showing, and the vertical offset for gravity, if any.

final TransformationMethod getTransformationMethod()

Gets the current TransformationMethod for the TextView.

Typeface getTypeface()

Gets the current Typeface that is used to style the text.

URLSpan[] getUrls()

Returns the list of URLSpans attached to the text (by Linkify or otherwise) if any.

boolean hasOverlappingRendering()

Returns whether this View has content which overlaps.

boolean hasSelection()

Return true iff there is a selection of nonzero length inside this text view.

void invalidateDrawable(Drawable drawable)

Invalidates the specified Drawable.

boolean isAllCaps()

Checks whether the transformation method applied to this TextView is set to ALL CAPS.

boolean isCursorVisible()
boolean isElegantTextHeight()

Get the value of the TextView's elegant height metrics flag.

boolean isFallbackLineSpacing()
final boolean isHorizontallyScrollable()

Returns whether the text is allowed to be wider than the View.

boolean isInputMethodTarget()

Returns whether this text view is a current input method target.

boolean isSingleLine()

Returns if the text is constrained to a single horizontally scrolling line ignoring new line characters instead of letting it wrap onto multiple lines.

boolean isSuggestionsEnabled()

Return whether or not suggestions are enabled on this TextView.

boolean isTextSelectable()

Returns the state of the textIsSelectable flag (See setTextIsSelectable()).

void jumpDrawablesToCurrentState()

Call Drawable.jumpToCurrentState() on all Drawable objects associated with this view.

int length()

Returns the length, in characters, of the text managed by this TextView

boolean moveCursorToVisibleOffset()

Move the cursor, if needed, so that it is at an offset that is visible to the user.

void onBeginBatchEdit()

Called by the framework in response to a request to begin a batch of edit operations through a call to link beginBatchEdit().

boolean onCheckIsTextEditor()

Check whether the called view is a text editor, in which case it would make sense to automatically display a soft input window for it.

void onCommitCompletion(CompletionInfo text)

Called by the framework in response to a text completion from the current input method, provided by it calling InputConnection.commitCompletion().

void onCommitCorrection(CorrectionInfo info)

Called by the framework in response to a text auto-correction (such as fixing a typo using a dictionary) from the current input method, provided by it calling InputConnection.commitCorrection().

InputConnection onCreateInputConnection(EditorInfo outAttrs)

Create a new InputConnection for an InputMethod to interact with the view.

void onCreateViewTranslationRequest(int[] supportedFormats, Consumer<ViewTranslationRequest> requestsCollector)

Collects a ViewTranslationRequest which represents the content to be translated in the view.

boolean onDragEvent(DragEvent event)

Handles drag events sent by the system following a call to startDragAndDrop().

void onEditorAction(int actionCode)

Called when an attached input method calls InputConnection.performEditorAction() for this text view.

void onEndBatchEdit()

Called by the framework in response to a request to end a batch of edit operations through a call to link endBatchEdit().

boolean onGenericMotionEvent(MotionEvent event)

Implement this method to handle generic motion events.

boolean onKeyDown(int keyCode, KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyDown(): perform press of the view when KeyEvent#KEYCODE_DPAD_CENTER or KeyEvent#KEYCODE_ENTER is released, if the view is enabled and clickable.

boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handle the event).

boolean onKeyPreIme(int keyCode, KeyEvent event)

Handle a key event before it is processed by any input method associated with the view hierarchy.

boolean onKeyShortcut(int keyCode, KeyEvent event)

Called on the focused view when a key shortcut event is not handled.

boolean onKeyUp(int keyCode, KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyUp(): perform clicking of the view when KeyEvent#KEYCODE_DPAD_CENTER, KeyEvent#KEYCODE_ENTER or KeyEvent#KEYCODE_SPACE is released.

boolean onPreDraw()

Callback method to be invoked when the view tree is about to be drawn.

boolean onPrivateIMECommand(String action, Bundle data)

Called by the framework in response to a private command from the current method, provided by it calling InputConnection.performPrivateCommand().

ContentInfo onReceiveContent(ContentInfo payload)

Default TextView implementation for receiving content.

PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex)

Returns the pointer icon for the motion event, or null if it doesn't specify the icon.

void onRestoreInstanceState(Parcelable state)

Hook allowing a view to re-apply a representation of its internal state that had previously been generated by onSaveInstanceState().

void onRtlPropertiesChanged(int layoutDirection)

Called when any RTL property (layout direction or text direction or text alignment) has been changed.

Parcelable onSaveInstanceState()

Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state.

void onScreenStateChanged(int screenState)

This method is called whenever the state of the screen this view is attached to changes.

boolean onTextContextMenuItem(int id)

Called when a context menu option for the text view is selected.

boolean onTouchEvent(MotionEvent event)

Implement this method to handle touch screen motion events.

boolean onTrackballEvent(MotionEvent event)

Implement this method to handle trackball 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.

void onWindowFocusChanged(boolean hasWindowFocus)

Called when the window containing this view gains or loses focus.

boolean performLongClick()

Calls this view's OnLongClickListener, if it is defined.

void removeTextChangedListener(TextWatcher watcher)

Removes the specified TextWatcher from the list of those whose methods are called whenever this TextView's text changes.

void sendAccessibilityEventUnchecked(AccessibilityEvent event)

This method behaves exactly as sendAccessibilityEvent(int) but takes as an argument an empty AccessibilityEvent and does not perform a check whether accessibility is enabled.

void setAllCaps(boolean allCaps)

Sets the properties of this field to transform input to ALL CAPS display.

final void setAutoLinkMask(int mask)

Sets the autolink mask of the text.

void setAutoSizeTextTypeUniformWithConfiguration(int autoSizeMinTextSize, int autoSizeMaxTextSize, int autoSizeStepGranularity, int unit)

Specify whether this widget should automatically scale the text to try to perfectly fit within the layout bounds.

void setAutoSizeTextTypeUniformWithPresetSizes(int[] presetSizes, int unit)

Specify whether this widget should automatically scale the text to try to perfectly fit within the layout bounds.

void setAutoSizeTextTypeWithDefaults(int autoSizeTextType)

Specify whether this widget should automatically scale the text to try to perfectly fit within the layout bounds by using the default auto-size configuration.

void setBreakStrategy(int breakStrategy)

Sets the break strategy for breaking paragraphs into lines.

void setCompoundDrawablePadding(int pad)

Sets the size of the padding between the compound drawables and the text.

void setCompoundDrawableTintBlendMode(BlendMode blendMode)

Specifies the blending mode used to apply the tint specified by setCompoundDrawableTintList(android.content.res.ColorStateList) to the compound drawables.

void setCompoundDrawableTintList(ColorStateList tint)

Applies a tint to the compound drawables.

void setCompoundDrawableTintMode(PorterDuff.Mode tintMode)

Specifies the blending mode used to apply the tint specified by setCompoundDrawableTintList(android.content.res.ColorStateList) to the compound drawables.

void setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom)

Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text.

void setCompoundDrawablesRelative(Drawable start, Drawable top, Drawable end, Drawable bottom)

Sets the Drawables (if any) to appear to the start of, above, to the end of, and below the text.

void setCompoundDrawablesRelativeWithIntrinsicBounds(Drawable start, Drawable top, Drawable end, Drawable bottom)

Sets the Drawables (if any) to appear to the start of, above, to the end of, and below the text.

void setCompoundDrawablesRelativeWithIntrinsicBounds(int start, int top, int end, int bottom)

Sets the Drawables (if any) to appear to the start of, above, to the end of, and below the text.

void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, Drawable right, Drawable bottom)

Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text.

void setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom)

Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text.

void setCursorVisible(boolean visible)

Set whether the cursor is visible.

void setCustomInsertionActionModeCallback(ActionMode.Callback actionModeCallback)

If provided, this ActionMode.Callback will be used to create the ActionMode when text insertion is initiated in this View.

void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback)

If provided, this ActionMode.Callback will be used to create the ActionMode when text selection is initiated in this View.

final void setEditableFactory(Editable.Factory factory)

Sets the Factory used to create new Editables.

void setElegantTextHeight(boolean elegant)

Set the TextView's elegant height metrics flag.

void setEllipsize(TextUtils.TruncateAt where)

Causes words in the text that are longer than the view's width to be ellipsized instead of broken in the middle.

void setEms(int ems)

Sets the width of the TextView to be exactly ems wide.

void setEnabled(boolean enabled)

Set the enabled state of this view.

void setError(CharSequence error)

Sets the right-hand compound drawable of the TextView to the "error" icon and sets an error message that will be displayed in a popup when the TextView has focus.

void setError(CharSequence error, Drawable icon)

Sets the right-hand compound drawable of the TextView to the specified icon and sets an error message that will be displayed in a popup when the TextView has focus.

void setExtractedText(ExtractedText text)

Apply to this text view the given extracted text, as previously returned by extractText(android.view.inputmethod.ExtractedTextRequest, android.view.inputmethod.ExtractedText).

void setFallbackLineSpacing(boolean enabled)

Set whether to respect the ascent and descent of the fallback fonts that are used in displaying the text (which is needed to avoid text from consecutive lines running into each other).

void setFilters(InputFilter[] filters)

Sets the list of input filters that will be used if the buffer is Editable.

void setFirstBaselineToTopHeight(int firstBaselineToTopHeight)

Updates the top padding of the TextView so that firstBaselineToTopHeight is the distance between the top of the TextView and first line's baseline.

void setFontFeatureSettings(String fontFeatureSettings)

Sets font feature settings.

boolean setFontVariationSettings(String fontVariationSettings)

Sets TrueType or OpenType font variation settings.

void setFreezesText(boolean freezesText)

Control whether this text view saves its entire text contents when freezing to an icicle, in addition to dynamic state such as cursor position.

void setGravity(int gravity)

Sets the horizontal alignment of the text and the vertical gravity that will be used when there is extra space in the TextView beyond what is required for the text itself.

void setHeight(int pixels)

Sets the height of the TextView to be exactly pixels tall.

void setHighlightColor(int color)

Sets the color used to display the selection highlight.

final void setHint(CharSequence hint)

Sets the text to be displayed when the text of the TextView is empty.

final void setHint(int resid)

Sets the text to be displayed when the text of the TextView is empty, from a resource.

final void setHintTextColor(ColorStateList colors)

Sets the color of the hint text.

final void setHintTextColor(int color)

Sets the color of the hint text for all the states (disabled, focussed, selected...) of this TextView.

void setHorizontallyScrolling(boolean whether)

Sets whether the text should be allowed to be wider than the View is.

void setHyphenationFrequency(int hyphenationFrequency)

Sets the frequency of automatic hyphenation to use when determining word breaks.

void setImeActionLabel(CharSequence label, int actionId)

Change the custom IME action associated with the text view, which will be reported to an IME with EditorInfo#actionLabel and EditorInfo#actionId when it has focus.

void setImeHintLocales(LocaleList hintLocales)

Change "hint" locales associated with the text view, which will be reported to an IME with EditorInfo#hintLocales when it has focus.

void setImeOptions(int imeOptions)

Change the editor type integer associated with the text view, which is reported to an Input Method Editor (IME) with EditorInfo#imeOptions when it has focus.

void setIncludeFontPadding(boolean includepad)

Set whether the TextView includes extra top and bottom padding to make room for accents that go above the normal ascent and descent.

void setInputExtras(int xmlResId)

Set the extra input data of the text, which is the TextBoxAttribute.extras Bundle that will be filled in when creating an input connection.

void setInputType(int type)

Set the type of the content with a constant as defined for EditorInfo#inputType.

void setJustificationMode(int justificationMode)

Set justification mode.

void setKeyListener(KeyListener input)

Sets the key listener to be used with this TextView.

void setLastBaselineToBottomHeight(int lastBaselineToBottomHeight)

Updates the bottom padding of the TextView so that lastBaselineToBottomHeight is the distance between the bottom of the TextView and the last line's baseline.

void setLetterSpacing(float letterSpacing)

Sets text letter-spacing in em units.

void setLineBreakStyle(int lineBreakStyle)

Sets the line-break style for text wrapping.

void setLineBreakWordStyle(int lineBreakWordStyle)

Sets the line-break word style for text wrapping.

void setLineHeight(int lineHeight)

Sets an explicit line height for this TextView.

void setLineSpacing(float add, float mult)

Sets line spacing for this TextView.

void setLines(int lines)

Sets the height of the TextView to be exactly lines tall.

final void setLinkTextColor(ColorStateList colors)

Sets the color of links in the text.

final void setLinkTextColor(int color)

Sets the color of links in the text.

final void setLinksClickable(boolean whether)

Sets whether the movement method will automatically be set to LinkMovementMethod if setAutoLinkMask(int) has been set to nonzero and links are detected in setText(char[], int, int).

void setMarqueeRepeatLimit(int marqueeLimit)

Sets how many times to repeat the marquee animation.

void setMaxEms(int maxEms)

Sets the width of the TextView to be at most maxEms wide.

void setMaxHeight(int maxPixels)

Sets the height of the TextView to be at most maxPixels tall.

void setMaxLines(int maxLines)

Sets the height of the TextView to be at most maxLines tall.

void setMaxWidth(int maxPixels)

Sets the width of the TextView to be at most maxPixels wide.

void setMinEms(int minEms)

Sets the width of the TextView to be at least minEms wide.

void setMinHeight(int minPixels)

Sets the height of the TextView to be at least minPixels tall.

void setMinLines(int minLines)

Sets the height of the TextView to be at least minLines tall.

void setMinWidth(int minPixels)

Sets the width of the TextView to be at least minPixels wide.

final void setMovementMethod(MovementMethod movement)

Sets the MovementMethod for handling arrow key movement for this TextView.

void setOnEditorActionListener(TextView.OnEditorActionListener l)

Set a special listener to be called when an action is performed on the text 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 setPaintFlags(int flags)

Sets flags on the Paint being used to display the text and reflows the text if they are different from the old flags.

void setPrivateImeOptions(String type)

Set the private content type of the text, which is the EditorInfo.privateImeOptions field that will be filled in when creating an input connection.

void setRawInputType(int type)

Directly change the content type integer of the text view, without modifying any other state.

void setScroller(Scroller s)

Sets the Scroller used for producing a scrolling animation

void setSelectAllOnFocus(boolean selectAllOnFocus)

Set the TextView so that when it takes focus, all the text is selected.

void setSelected(boolean selected)

Changes the selection state of this view.

void setShadowLayer(float radius, float dx, float dy, int color)

Gives the text a shadow of the specified blur radius and color, the specified distance from its drawn position.

final void setShowSoftInputOnFocus(boolean show)

Sets whether the soft input method will be made visible when this TextView gets focused.

void setSingleLine(boolean singleLine)

If true, sets the properties of this field (number of lines, horizontally scrolling, transformation method) to be for a single-line input; if false, restores these to the default conditions.

void setSingleLine()

Sets the properties of this field (lines, horizontally scrolling, transformation method) to be for a single-line input.

final void setSpannableFactory(Spannable.Factory factory)

Sets the Factory used to create new Spannables.

final void setText(int resid)

Sets the text to be displayed using a string resource identifier.

final void setText(CharSequence text)

Sets the text to be displayed.

void setText(CharSequence text, TextView.BufferType type)

Sets the text to be displayed and the TextView.BufferType.

final void setText(int resid, TextView.BufferType type)

Sets the text to be displayed using a string resource identifier and the TextView.BufferType.

final void setText(char[] text, int start, int len)

Sets the TextView to display the specified slice of the specified char array.

void setTextAppearance(Context context, int resId)

This method was deprecated in API level 23. Use setTextAppearance(int) instead.

void setTextAppearance(int resId)

Sets the text appearance from the specified style resource.

void setTextClassifier(TextClassifier textClassifier)

Sets the TextClassifier for this TextView.

void setTextColor(int color)

Sets the text color for all the states (normal, selected, focused) to be this color.

void setTextColor(ColorStateList colors)

Sets the text color.

void setTextCursorDrawable(Drawable textCursorDrawable)

Sets the Drawable corresponding to the text cursor.

void setTextCursorDrawable(int textCursorDrawable)

Sets the Drawable corresponding to the text cursor.

void setTextIsSelectable(boolean selectable)

Sets whether the content of this view is selectable by the user.

final void setTextKeepState(CharSequence text)

Sets the text to be displayed but retains the cursor position.

final void setTextKeepState(CharSequence text, TextView.BufferType type)

Sets the text to be displayed and the TextView.BufferType but retains the cursor position.

void setTextLocale(Locale locale)

Set the default Locale of the text in this TextView to a one-member LocaleList containing just the given Locale.

void setTextLocales(LocaleList locales)

Set the default LocaleList of the text in this TextView to the given value.

void setTextMetricsParams(PrecomputedText.Params params)

Apply the text layout parameter.

void setTextScaleX(float size)

Sets the horizontal scale factor for text.

void setTextSelectHandle(int textSelectHandle)

Sets the Drawable corresponding to the selection handle used for positioning the cursor within text.

void setTextSelectHandle(Drawable textSelectHandle)

Sets the Drawable corresponding to the selection handle used for positioning the cursor within text.

void setTextSelectHandleLeft(int textSelectHandleLeft)

Sets the Drawable corresponding to the left handle used for selecting text.

void setTextSelectHandleLeft(Drawable textSelectHandleLeft)

Sets the Drawable corresponding to the left handle used for selecting text.

void setTextSelectHandleRight(Drawable textSelectHandleRight)

Sets the Drawable corresponding to the right handle used for selecting text.

void setTextSelectHandleRight(int textSelectHandleRight)

Sets the Drawable corresponding to the right handle used for selecting text.

void setTextSize(int unit, float size)

Set the default text size to a given unit and value.

void setTextSize(float size)

Set the default text size to the given value, interpreted as "scaled pixel" units.

final void setTransformationMethod(TransformationMethod method)

Sets the transformation that is applied to the text that this TextView is displaying.

void setTypeface(Typeface tf)

Sets the typeface and style in which the text should be displayed.

void setTypeface(Typeface tf, int style)

Sets the typeface and style in which the text should be displayed, and turns on the fake bold and italic bits in the Paint if the Typeface that you provided does not have all the bits in the style that you specified.

void setWidth(int pixels)

Sets the width of the TextView to be exactly pixels wide.

boolean showContextMenu()

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.

Protected methods

int computeHorizontalScrollRange()

Compute the horizontal range that the horizontal scrollbar represents.

int computeVerticalScrollExtent()

Compute the vertical extent of the vertical scrollbar's thumb within the vertical range.

int computeVerticalScrollRange()

Compute the vertical range that the vertical scrollbar represents.

void drawableStateChanged()

This function is called whenever the state of the view changes in such a way that it impacts the state of drawables being shown.

int getBottomPaddingOffset()

Amount by which to extend the bottom fading region.

boolean getDefaultEditable()

Subclasses override this to specify that they have a KeyListener by default even if not specifically called for in the XML options.

MovementMethod getDefaultMovementMethod()

Subclasses override this to specify a default movement method.

float getLeftFadingEdgeStrength()

Returns the strength, or intensity, of the left faded edge.

int getLeftPaddingOffset()

Amount by which to extend the left fading region.

float getRightFadingEdgeStrength()

Returns the strength, or intensity, of the right faded edge.

int getRightPaddingOffset()

Amount by which to extend the right fading region.

int getTopPaddingOffset()

Amount by which to extend the top fading region.

boolean isPaddingOffsetRequired()

If the View draws content inside its padding and enables fading edges, it needs to support padding offsets.

void onAttachedToWindow()

This is called when the view is attached to a window.

void onConfigurationChanged(Configuration newConfig)

Called when the current configuration of the resources being used by the application have changed.

void onCreateContextMenu(ContextMenu menu)

Views should implement this if the view itself is going to add items to the context menu.

int[] onCreateDrawableState(int extraSpace)

Generate the new Drawable state for this view.

void onDraw(Canvas canvas)

Implement this to do your drawing.

void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect)

Called by the view system when the focus state of this view changes.

void onLayout(boolean changed, int left, int top, int right, int bottom)

Called from layout when this view should assign a size and position to each of its children.

void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height.

void onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert)

This is called in response to an internal scroll in this view (i.e., the view scrolled its own contents).

void onSelectionChanged(int selStart, int selEnd)

This method is called when the selection has changed, in case any subclasses would like to know.

void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter)

This method is called when the text is changed, in case any subclasses would like to know.

void onVisibilityChanged(View changedView, int visibility)

Called when the visibility of the view or an ancestor of the view has changed.

boolean setFrame(int l, int t, int r, int b)
boolean verifyDrawable(Drawable who)

If your view subclass is displaying its own Drawable objects, it should override this function and return true for any Drawable it is displaying.

Inherited methods

From class android.view.View

void addChildrenForAccessibility(ArrayList<View> outChildren)

Adds the children of this View relevant for accessibility to the given list as output.

void addExtraDataToAccessibilityNodeInfo(AccessibilityNodeInfo info, String extraDataKey, Bundle arguments)

Adds extra data to an AccessibilityNodeInfo based on an explicit request for the additional data.

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 addOnAttachStateChangeListener(View.OnAttachStateChangeListener listener)

Add a listener for attach state changes.

void addOnLayoutChangeListener(View.OnLayoutChangeListener listener)

Add a listener that will be called when the bounds of the view change due to layout processing.

void addOnUnhandledKeyEventListener(View.OnUnhandledKeyEventListener listener)

Adds a listener which will receive unhandled KeyEvents.

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.

ViewPropertyAnimator animate()

This method returns a ViewPropertyAnimator object, which can be used to animate specific properties on this View.

void announceForAccessibility(CharSequence text)

Convenience method for sending a AccessibilityEvent#TYPE_ANNOUNCEMENT AccessibilityEvent to suggest that an accessibility service announce the specified text to its users.

void autofill(AutofillValue value)

Automatically fills the content of this view with the value.

void autofill(SparseArray<AutofillValue> values)

Automatically fills the content of the virtual children within this view.

boolean awakenScrollBars(int startDelay, boolean invalidate)

Trigger the scrollbars to draw.

boolean awakenScrollBars(int startDelay)

Trigger the scrollbars to draw.

boolean awakenScrollBars()

Trigger the scrollbars to draw.

void bringToFront()

Change the view's z order in the tree, so it's on top of other sibling views.

void buildDrawingCache(boolean autoScale)

This method was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

void buildDrawingCache()

This method was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

void buildLayer()

Forces this view's layer to be created and this view to be rendered into its layer.

boolean callOnClick()

Directly call any attached OnClickListener.

boolean canResolveLayoutDirection()

Check if layout direction resolution can be done.

boolean canResolveTextAlignment()

Check if text alignment resolution can be done.

boolean canResolveTextDirection()

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.

final void cancelDragAndDrop()

Cancels an ongoing drag and drop operation.

void cancelLongPress()

Cancels a pending long press.

final void cancelPendingInputEvents()

Cancel any deferred high-level input events that were previously posted to the event queue.

boolean checkInputConnectionProxy(View view)

Called by the InputMethodManager when a view who is not the current input connection target is trying to make a call on the manager.

void clearAnimation()

Cancels any animations for this view.

void clearFocus()

Called when this view wants to give up focus.

void clearViewTranslationCallback()

Clear the ViewTranslationCallback from this view.

static int combineMeasuredStates(int curState, int newState)

Merge two states as returned by getMeasuredState().

int computeHorizontalScrollExtent()

Compute the horizontal extent of the horizontal scrollbar's thumb within the horizontal range.

int computeHorizontalScrollOffset()

Compute the horizontal offset of the horizontal scrollbar's thumb within the horizontal range.

int computeHorizontalScrollRange()

Compute the horizontal range that the horizontal scrollbar represents.

void computeScroll()

Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary.

WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets)

Compute insets that should be consumed by this view and the ones that should propagate to those under it.

int computeVerticalScrollExtent()

Compute the vertical extent of the vertical scrollbar's thumb within the vertical range.

int computeVerticalScrollOffset()

Compute the vertical offset of the vertical scrollbar's thumb within the horizontal range.

int computeVerticalScrollRange()

Compute the vertical range that the vertical scrollbar represents.

AccessibilityNodeInfo createAccessibilityNodeInfo()

Returns an AccessibilityNodeInfo representing this view from the point of view of an AccessibilityService.

void createContextMenu(ContextMenu menu)

Show the context menu for this view.

void destroyDrawingCache()

This method was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

WindowInsets dispatchApplyWindowInsets(WindowInsets insets)

Request to apply the given window insets to this view or another view in its subtree.

boolean dispatchCapturedPointerEvent(MotionEvent event)

Pass a captured pointer event down to the focused view.

void dispatchConfigurationChanged(Configuration newConfig)

Dispatch a notification about a resource configuration change down the view hierarchy.

void dispatchCreateViewTranslationRequest(Map<AutofillId, long[]> viewIds, int[] supportedFormats, TranslationCapability capability, List<ViewTranslationRequest> requests)

Dispatch to collect the ViewTranslationRequests for translation purpose by traversing the hierarchy when the app requests ui translation.

void dispatchDisplayHint(int hint)

Dispatch a hint about whether this view is displayed.

boolean dispatchDragEvent(DragEvent event)

Detects if this View is enabled and has a drag event listener.

void dispatchDraw(Canvas canvas)

Called by draw to draw the child views.

void dispatchDrawableHotspotChanged(float x, float y)

Dispatches drawableHotspotChanged to all of this View's children.

void dispatchFinishTemporaryDetach()

Dispatch onFinishTemporaryDetach() to this View and its direct children if this is a container View.

boolean dispatchGenericFocusedEvent(MotionEvent event)

Dispatch a generic motion event to the currently focused view.

boolean dispatchGenericMotionEvent(MotionEvent event)

Dispatch a generic motion event.

boolean dispatchGenericPointerEvent(MotionEvent event)

Dispatch a generic motion event to the view under the first pointer.

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 dispatchKeyEventPreIme(KeyEvent event)

Dispatch a key event before it is processed by any input method associated with the view hierarchy.

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 dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments)

Report an accessibility action to this view's parents for delegated processing.

boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow)

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)

Dispatch one step of a nested scroll in progress.

void dispatchPointerCaptureChanged(boolean hasCapture)
boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event)

Dispatches an AccessibilityEvent to the View first and then to its children for adding their text content to the event.

void dispatchProvideAutofillStructure(ViewStructure structure, int flags)

Dispatches creation of a ViewStructures for autofill purposes down the hierarchy, when an Assist structure is being created as part of an autofill request.

void dispatchProvideStructure(ViewStructure structure)

Dispatch creation of ViewStructure down the hierarchy.

void dispatchRestoreInstanceState(SparseArray<Parcelable> container)

Called by restoreHierarchyState(android.util.SparseArray) to retrieve the state for this view and its children.

void dispatchSaveInstanceState(SparseArray<Parcelable> container)

Called by saveHierarchyState(android.util.SparseArray) to store the state for this view and its children.

void dispatchScrollCaptureSearch(Rect localVisibleRect, Point windowOffset, Consumer<ScrollCaptureTarget> targets)

Dispatch a scroll capture search request down the view hierarchy.

void dispatchSetActivated(boolean activated)

Dispatch setActivated to all of this View's children.

void dispatchSetPressed(boolean pressed)

Dispatch setPressed to all of this View's children.

void dispatchSetSelected(boolean selected)

Dispatch setSelected to all of this View's children.

void dispatchStartTemporaryDetach()

Dispatch onStartTemporaryDetach() to this View and its direct children if this is a container View.

void dispatchSystemUiVisibilityChanged(int visibility)

This method was deprecated in API level 30. Use WindowInsets#isVisible(int) to find out about system bar visibilities by setting a OnApplyWindowInsetsListener on this view.

boolean dispatchTouchEvent(MotionEvent event)

Pass the touch screen motion event down to the target view, or this view if it is the target.

boolean dispatchTrackballEvent(MotionEvent event)

Pass a trackball motion event down to the focused view.

boolean dispatchUnhandledMove(View focused, int direction)

This method is the last chance for the focused view and its ancestors to respond to an arrow key.

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 dispatchWindowInsetsAnimationEnd(WindowInsetsAnimation animation)

Dispatches WindowInsetsAnimation.Callback#onEnd(WindowInsetsAnimation) when Window Insets animation ends.

void dispatchWindowInsetsAnimationPrepare(WindowInsetsAnimation animation)

Dispatches WindowInsetsAnimation.Callback#onPrepare(WindowInsetsAnimation) when Window Insets animation is being prepared.

WindowInsets dispatchWindowInsetsAnimationProgress(WindowInsets insets, List<WindowInsetsAnimation> runningAnimations)

Dispatches WindowInsetsAnimation.Callback#onProgress(WindowInsets, List) when Window Insets animation makes progress.

WindowInsetsAnimation.Bounds dispatchWindowInsetsAnimationStart(WindowInsetsAnimation animation, WindowInsetsAnimation.Bounds bounds)

Dispatches WindowInsetsAnimation.Callback#onStart(WindowInsetsAnimation, Bounds) when Window Insets animation is started.

void dispatchWindowSystemUiVisiblityChanged(int visible)

This method was deprecated in API level 30. SystemUiVisibility flags are deprecated. Use WindowInsetsController instead.

void dispatchWindowVisibilityChanged(int visibility)

Dispatch a window visibility change down the view hierarchy.

void draw(Canvas canvas)

Manually render this view (and all of its 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.

void drawableStateChanged()

This function is called whenever the state of the view changes in such a way that it impacts the state of drawables being shown.

View findFocus()

Find the view in the hierarchy rooted at this view that currently has focus.

final OnBackInvokedDispatcher findOnBackInvokedDispatcher()

Walk up the View hierarchy to find the nearest OnBackInvokedDispatcher.

final <T extends View> T findViewById(int id)

Finds the first descendant view with the given ID, the view itself if the ID matches getId(), or null if the ID is invalid (< 0) or there is no matching view in the hierarchy.

final <T extends View> T findViewWithTag(Object tag)

Look for a child view with the given tag.

void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags)

Finds the Views that contain given text.

boolean fitSystemWindows(Rect insets)

This method was deprecated in API level 20. As of API 20 use dispatchApplyWindowInsets(android.view.WindowInsets) to apply insets to views. Views should override onApplyWindowInsets(android.view.WindowInsets) or use setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener) to implement handling their own insets.

View 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 (see hasOverlappingRendering() for more details on this behavior).

void forceLayout()

Forces this view to be laid out during the next layout pass.

boolean gatherTransparentRegion(Region region)

This is used by the ViewRoot to perform an optimization when the view hierarchy contains one or several SurfaceView.

void generateDisplayHash(String hashAlgorithm, Rect bounds, Executor executor, DisplayHashResultCallback callback)

Called to generate a DisplayHash for this view.

static int generateViewId()

Generate a value suitable for use in setId(int).

CharSequence getAccessibilityClassName()

Return the class name of this object to be used for accessibility purposes.

View.AccessibilityDelegate getAccessibilityDelegate()

Returns the delegate for implementing accessibility support via composition.

int getAccessibilityLiveRegion()

Gets the live region mode for this View.

AccessibilityNodeProvider getAccessibilityNodeProvider()

Gets the provider for managing a virtual view hierarchy rooted at this View and reported to AccessibilityServices that explore the window content.

CharSequence getAccessibilityPaneTitle()

Get the title of the pane for purposes of accessibility.

int getAccessibilityTraversalAfter()

Gets the id of a view after which this one is visited in accessibility traversal.

int getAccessibilityTraversalBefore()

Gets the id of a view before which this one is visited in accessibility traversal.

float getAlpha()

The opacity of the view.

Animation getAnimation()

Get the animation currently associated with this view.

Matrix getAnimationMatrix()

Return the current transformation matrix of the view.

IBinder getApplicationWindowToken()

Retrieve a unique token identifying the top-level "real" window of the window that this view is attached to.

int[] getAttributeResolutionStack(int attribute)

Returns the ordered list of resource ID that are considered when resolving attribute values for this View.

Map<Integer, Integer> getAttributeSourceResourceMap()

Returns the mapping of attribute resource ID to source resource ID where the attribute value was set.

String[] getAutofillHints()

Gets the hints that help an AutofillService determine how to autofill the view with the user's data.

final AutofillId getAutofillId()

Gets the unique, logical identifier of this view in the activity, for autofill purposes.

int getAutofillType()

Describes the autofill type of this view, so an AutofillService can create the proper AutofillValue when autofilling the view.

AutofillValue getAutofillValue()

Gets the View's current autofill value.

Drawable getBackground()

Gets the background drawable

BlendMode getBackgroundTintBlendMode()

Return the blending mode used to apply the tint to the background drawable, if specified.

ColorStateList getBackgroundTintList()

Return the tint applied to the background drawable, if specified.

PorterDuff.Mode getBackgroundTintMode()

Return the blending mode used to apply the tint to the background drawable, if specified.

int getBaseline()

Return the offset of the widget's text baseline from the widget's top boundary.

final int getBottom()

Bottom position of this view relative to its parent.

float getBottomFadingEdgeStrength()

Returns the strength, or intensity, of the bottom faded edge.

int getBottomPaddingOffset()

Amount by which to extend the bottom fading region.

float getCameraDistance()

Gets the distance along the Z axis from the camera to this view.

boolean getClipBounds(Rect outRect)

Populates an output rectangle with the clip bounds of the view, returning true if successful or false if the view's clip bounds are null.

Rect getClipBounds()

Returns a copy of the current clipBounds.

final boolean getClipToOutline()

Returns whether the Outline should be used to clip the contents of the View.

final ContentCaptureSession getContentCaptureSession()

Gets the session used to notify content capture events.

CharSequence getContentDescription()

Returns the View's content description.

final Context getContext()

Returns the context the view is running in, through which it can access the current theme, resources, etc.

ContextMenu.ContextMenuInfo getContextMenuInfo()

Views should implement this if they have extra information to associate with the context menu.

final boolean getDefaultFocusHighlightEnabled()

Returns whether this View should use a default focus highlight when it gets focused but doesn't have R.attr.state_focused defined in its background.

static int getDefaultSize(int size, int measureSpec)

Utility to return a default size.

Display getDisplay()

Gets the logical display to which the view's window has been attached.

final int[] getDrawableState()

Return an array of resource IDs of the drawable states representing the current state of the view.

Bitmap getDrawingCache()

This method was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

Bitmap getDrawingCache(boolean autoScale)

This method was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

int getDrawingCacheBackgroundColor()

This method was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

int getDrawingCacheQuality()

This method was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

void getDrawingRect(Rect outRect)

Return the visible drawing bounds of your view.

long getDrawingTime()

Return the time at which the drawing of the view hierarchy started.

float getElevation()

The base elevation of this view relative to its parent, in pixels.

int getExplicitStyle()

Returns the resource ID for the style specified using style="..." in the AttributeSet's backing XML element or Resources#ID_NULL otherwise if not specified or otherwise not applicable.

boolean getFilterTouchesWhenObscured()

Gets whether the framework should discard touches when the view's window is obscured by another visible window at the touched location.

boolean getFitsSystemWindows()

Check for state of setFitsSystemWindows(boolean).

int getFocusable()

Returns the focusable setting for this view.

ArrayList<View> getFocusables(int direction)

Find and return all focusable views that are descendants of this view, possibly including this view if it is focusable itself.

void getFocusedRect(Rect r)

When a view has focus and the user navigates away from it, the next view is searched for starting from the rectangle filled in by this method.

Drawable getForeground()

Returns the drawable used as the foreground of this View.

int getForegroundGravity()

Describes how the foreground is positioned.

BlendMode getForegroundTintBlendMode()

Return the blending mode used to apply the tint to the foreground drawable, if specified.

ColorStateList getForegroundTintList()

Return the tint applied to the foreground drawable, if specified.

PorterDuff.Mode getForegroundTintMode()

Return the blending mode used to apply the tint to the foreground drawable, if specified.

final boolean getGlobalVisibleRect(Rect r)

Sets r to the coordinates of the non-clipped area of this view in the coordinate space of the view's root view.

boolean getGlobalVisibleRect(Rect r, Point globalOffset)

Sets r to the coordinates of the non-clipped area of this view in the coordinate space of the view's root view.

Handler getHandler()
final boolean getHasOverlappingRendering()

Returns the value for overlapping rendering that is used internally.

final int getHeight()

Return the height of your view.

void getHitRect(Rect outRect)

Hit rectangle in parent's coordinates

int getHorizontalFadingEdgeLength()

Returns the size of the horizontal faded edges used to indicate that more content in this view is visible.

int getHorizontalScrollbarHeight()

Returns the height of the horizontal scrollbar.

Drawable getHorizontalScrollbarThumbDrawable()

Returns the currently configured Drawable for the thumb of the horizontal scroll bar if it exists, null otherwise.

Drawable getHorizontalScrollbarTrackDrawable()

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.

int getImportantForAccessibility()

Gets the mode for determining whether this View is important for accessibility.

int getImportantForAutofill()

Gets the mode for determining whether this view is important for autofill.

int getImportantForContentCapture()

Gets the mode for determining whether this view is important for content capture.

boolean getKeepScreenOn()

Returns whether the screen should remain on, corresponding to the current value of KEEP_SCREEN_ON.

KeyEvent.DispatcherState getKeyDispatcherState()

Return the global KeyEvent.DispatcherState for this view's window.

int getLabelFor()

Gets the id of a view for which this view serves as a label for accessibility purposes.

int getLayerType()

Indicates what type of layer is currently associated with this view.

int getLayoutDirection()

Returns the resolved layout direction for this view.

ViewGroup.LayoutParams getLayoutParams()

Get the LayoutParams associated with this view.

final int getLeft()

Left position of this view relative to its parent.

float getLeftFadingEdgeStrength()

Returns the strength, or intensity, of the left faded edge.

int getLeftPaddingOffset()

Amount by which to extend the left fading region.

final boolean getLocalVisibleRect(Rect r)

Sets r to the coordinates of the non-clipped area of this view relative to the top left corner of the view.

void getLocationInSurface(int[] location)

Gets the coordinates of this view in the coordinate space of the Surface that contains the view.

void getLocationInWindow(int[] outLocation)

Gets the coordinates of this view in the coordinate space of the window that contains the view, irrespective of system decorations.

void getLocationOnScreen(int[] outLocation)

Gets the coordinates of this view in the coordinate space of the device screen, irrespective of system decorations and whether the system is in multi-window mode.

Matrix getMatrix()

The transform matrix of this view, which is calculated based on the current rotation, scale, and pivot properties.

final int getMeasuredHeight()

Like getMeasuredHeightAndState(), but only returns the raw height component (that is the result is masked by MEASURED_SIZE_MASK).

final int getMeasuredHeightAndState()

Return the full height measurement information for this view as computed by the most recent call to measure(int, int).

final int getMeasuredState()

Return only the state bits of getMeasuredWidthAndState() and getMeasuredHeightAndState(), combined into one integer.

final int getMeasuredWidth()

Like getMeasuredWidthAndState(), but only returns the raw width component (that is the result is masked by MEASURED_SIZE_MASK).

final int getMeasuredWidthAndState()

Return the full width measurement information for this view as computed by the most recent call to measure(int, int).

int getMinimumHeight()

Returns the minimum height of the view.

int getMinimumWidth()

Returns the minimum width of the view.

int getNextClusterForwardId()

Gets the id of the root of the next keyboard navigation cluster.

int getNextFocusDownId()

Gets the id of the view to use when the next focus is FOCUS_DOWN.

int getNextFocusForwardId()

Gets the id of the view to use when the next focus is FOCUS_FORWARD.

int getNextFocusLeftId()

Gets the id of the view to use when the next focus is FOCUS_LEFT.

int getNextFocusRightId()

Gets the id of the view to use when the next focus is FOCUS_RIGHT.

int getNextFocusUpId()

Gets the id of the view to use when the next focus is FOCUS_UP.

View.OnFocusChangeListener getOnFocusChangeListener()

Returns the focus-change callback registered for this view.

int getOutlineAmbientShadowColor()
ViewOutlineProvider getOutlineProvider()

Returns the current ViewOutlineProvider of the view, which generates the Outline that defines the shape of the shadow it casts, and enables outline clipping.

int getOutlineSpotShadowColor()
int getOverScrollMode()

Returns the over-scroll mode for this view.

ViewOverlay getOverlay()

Returns the overlay for this view, creating it if it does not yet exist.

int getPaddingBottom()

Returns the bottom padding of this view.

int getPaddingEnd()

Returns the end padding of this view depending on its resolved layout direction.

int getPaddingLeft()

Returns the left padding of this view.

int getPaddingRight()

Returns the right padding of this view.

int getPaddingStart()

Returns the start padding of this view depending on its resolved layout direction.

int getPaddingTop()

Returns the top padding of this view.

final ViewParent getParent()

Gets the parent of this view.

ViewParent getParentForAccessibility()

Gets the parent for accessibility purposes.

float getPivotX()

The x location of the point around which the view is rotated and scaled.

float getPivotY()

The y location of the point around which the view is rotated and scaled.

PointerIcon getPointerIcon()

Gets the pointer icon for the current view.

final List<Rect> getPreferKeepClearRects()
String[] getReceiveContentMimeTypes()

Returns the MIME types accepted by performReceiveContent(ContentInfo) for this view, as configured via setOnReceiveContentListener(String[], OnReceiveContentListener).

Resources getResources()

Returns the resources associated with this view.

final boolean getRevealOnFocusHint()

Returns this view's preference for reveal behavior when it gains focus.

final int getRight()

Right position of this view relative to its parent.

float getRightFadingEdgeStrength()

Returns the strength, or intensity, of the right faded edge.

int getRightPaddingOffset()

Amount by which to extend the right fading region.

AttachedSurfaceControl getRootSurfaceControl()

The AttachedSurfaceControl itself is not a View, it is just the interface to the windowing-system object that contains the entire view hierarchy.

View getRootView()

Finds the topmost view in the current view hierarchy.

WindowInsets getRootWindowInsets()

Provide original WindowInsets that are dispatched to the view hierarchy.

float getRotation()

The degrees that the view is rotated around the pivot point.

float getRotationX()

The degrees that the view is rotated around the horizontal axis through the pivot point.

float getRotationY()

The degrees that the view is rotated around the vertical axis through the pivot point.

float getScaleX()

The amount that the view is scaled in x around the pivot point, as a proportion of the view's unscaled width.

float getScaleY()

The amount that the view is scaled in y around the pivot point, as a proportion of the view's unscaled height.

int getScrollBarDefaultDelayBeforeFade()

Returns the delay before scrollbars fade.

int getScrollBarFadeDuration()

Returns the scrollbar fade duration.

int getScrollBarSize()

Returns the scrollbar size.

int getScrollBarStyle()

Returns the current scrollbar style.

int getScrollCaptureHint()

Returns the current scroll capture hint for this view.

int getScrollIndicators()

Returns a bitmask representing the enabled scroll indicators.

final int getScrollX()

Return the scrolled left position of this view.

final int getScrollY()

Return the scrolled top position of this view.

int getSolidColor()

Override this if your view is known to always be drawn on top of a solid color background, and needs to draw fading edges.

int getSourceLayoutResId()

A View can be inflated from an XML layout.

final CharSequence getStateDescription()

Returns the View's state description.

StateListAnimator getStateListAnimator()

Returns the current StateListAnimator if exists.

int getSuggestedMinimumHeight()

Returns the suggested minimum height that the view should use.

int getSuggestedMinimumWidth()

Returns the suggested minimum width that the view should use.

List<Rect> getSystemGestureExclusionRects()

Retrieve the list of areas within this view's post-layout coordinate space where the system should not intercept touch or other pointing device gestures.

int getSystemUiVisibility()

This method was deprecated in API level 30. SystemUiVisibility flags are deprecated. Use WindowInsetsController instead.

Object getTag()

Returns this view's tag.

Object getTag(int key)

Returns the tag associated with this view and the specified key.

int getTextAlignment()

Return the resolved text alignment.

int getTextDirection()

Return the resolved text direction.

CharSequence getTooltipText()

Returns the view's tooltip text.

final int getTop()

Top position of this view relative to its parent.

float getTopFadingEdgeStrength()

Returns the strength, or intensity, of the top faded edge.

int getTopPaddingOffset()

Amount by which to extend the top fading region.

TouchDelegate getTouchDelegate()

Gets the TouchDelegate for this View.

ArrayList<View> getTouchables()

Find and return all touchable views that are descendants of this view, possibly including this view if it is touchable itself.

float getTransitionAlpha()

This property is intended only for use by the Fade transition, which animates it to produce a visual translucency that does not side-effect (or get affected by) the real alpha property.

String getTransitionName()

Returns the name of the View to be used to identify Views in Transitions.

float getTranslationX()

The horizontal location of this view relative to its left position.

float getTranslationY()

The vertical location of this view relative to its top position.

float getTranslationZ()

The depth location of this view relative to its elevation.

long getUniqueDrawingId()

Get the identifier used for this view by the drawing system.

int getVerticalFadingEdgeLength()

Returns the size of the vertical faded edges used to indicate that more content in this view is visible.

int getVerticalScrollbarPosition()
Drawable getVerticalScrollbarThumbDrawable()

Returns the currently configured Drawable for the thumb of the vertical scroll bar if it exists, null otherwise.

Drawable getVerticalScrollbarTrackDrawable()

Returns the currently configured Drawable for the track of the vertical scroll bar if it exists, null otherwise.

int getVerticalScrollbarWidth()

Returns the width of the vertical scrollbar.

ViewTranslationResponse getViewTranslationResponse()

Returns the ViewTranslationResponse associated with this view.

ViewTreeObserver getViewTreeObserver()

Returns the ViewTreeObserver for this view's hierarchy.

int getVisibility()

Returns the visibility status for this view.

final int getWidth()

Return the width of your view.

int getWindowAttachCount()
WindowId getWindowId()

Retrieve the WindowId for the window this view is currently attached to.

WindowInsetsController getWindowInsetsController()

Retrieves the single WindowInsetsController of the window this view is attached to.

int getWindowSystemUiVisibility()

This method was deprecated in API level 30. SystemUiVisibility flags are deprecated. Use WindowInsetsController instead.

IBinder getWindowToken()

Retrieve a unique token identifying the window this view is attached to.

int getWindowVisibility()

Returns the current visibility of the window this view is attached to (either GONE, INVISIBLE, or VISIBLE).

void getWindowVisibleDisplayFrame(Rect outRect)

Retrieve the overall visible display size in which the window this view is attached to has been positioned in.

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.

boolean hasExplicitFocusable()

Returns true if this view is focusable or if it contains a reachable View for which hasExplicitFocusable() returns true.

boolean hasFocus()

Returns true if this view has focus itself, or is the ancestor of the view that has focus.

boolean hasFocusable()

Returns true if this view is focusable or if it contains a reachable View for which hasFocusable() returns true.

boolean hasNestedScrollingParent()

Returns true if this view has a nested scrolling parent.

boolean hasOnClickListeners()

Return whether this view has an attached OnClickListener.

boolean hasOnLongClickListeners()

Return whether this view has an attached OnLongClickListener.

boolean hasOverlappingRendering()

Returns whether this View has content which overlaps.

boolean hasPointerCapture()

Checks pointer capture status.

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.

boolean hasWindowFocus()

Returns true if this view is in a window that currently has window focus.

static View inflate(Context context, int resource, ViewGroup root)

Inflate a view from an XML resource.

void invalidate()

Invalidate the whole view.

void invalidate(Rect dirty)

This method was deprecated in API level 28. The switch to hardware accelerated rendering in API 14 reduced the importance of the dirty rectangle. In API 21 the given rectangle is ignored entirely in favor of an internally-calculated area instead. Because of this, clients are encouraged to just call invalidate().

void invalidate(int l, int t, int r, int b)

This method was deprecated in API level 28. The switch to hardware accelerated rendering in API 14 reduced the importance of the dirty rectangle. In API 21 the given rectangle is ignored entirely in favor of an internally-calculated area instead. Because of this, clients are encouraged to just call invalidate().

void invalidateDrawable(Drawable drawable)

Invalidates the specified Drawable.

void invalidateOutline()

Called to rebuild this View's Outline from its outline provider

boolean isAccessibilityFocused()

Returns whether this View is accessibility focused.

boolean isAccessibilityHeading()

Gets whether this view is a heading for accessibility purposes.

boolean isActivated()

Indicates the activation state of this view.

boolean isAttachedToWindow()

Returns true if this view is currently attached to a window.

boolean isAutoHandwritingEnabled()

Return whether the View allows automatic handwriting initiation.

boolean isClickable()

Indicates whether this view reacts to click events or not.

boolean isContextClickable()

Indicates whether this view reacts to context clicks or not.

boolean isDirty()

True if this view has changed since the last time being drawn.

boolean isDrawingCacheEnabled()

This method was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

boolean isDuplicateParentStateEnabled()

Indicates whether this duplicates its drawable state from its parent.

boolean isEnabled()

Returns the enabled status for this view.

final boolean isFocusable()

Returns whether this View is currently able to take focus.

final boolean isFocusableInTouchMode()

When a view is focusable, it may not want to take focus when in touch mode.

boolean isFocused()

Returns true if this view has focus

final boolean isFocusedByDefault()

Returns whether this View should receive focus when the focus is restored for the view hierarchy containing this view.

boolean isForceDarkAllowed()

See setForceDarkAllowed(boolean)

boolean isHapticFeedbackEnabled()
boolean isHardwareAccelerated()

Indicates whether this view is attached to a hardware accelerated window or not.

boolean isHorizontalFadingEdgeEnabled()

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

boolean isHorizontalScrollBarEnabled()

Indicate whether the horizontal scrollbar should be drawn or not.

boolean isHovered()

Returns true if the view is currently hovered.

boolean isImportantForAccessibility()

Computes whether this view should be exposed for accessibility.

final boolean isImportantForAutofill()

Hints the Android System whether the AssistStructure.ViewNode associated with this view is considered important for autofill purposes.

final boolean isImportantForContentCapture()

Hints the Android System whether this view is considered important for content capture, based on the value explicitly set by setImportantForContentCapture(int) and heuristics when it's IMPORTANT_FOR_CONTENT_CAPTURE_AUTO.

boolean isInEditMode()

Indicates whether this View is currently in edit mode.

boolean isInLayout()

Returns whether the view hierarchy is currently undergoing a layout pass.

boolean isInTouchMode()

Returns whether the device is currently in touch mode.

final boolean isKeyboardNavigationCluster()

Returns whether this View is a root of a keyboard navigation cluster.

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.

boolean isLayoutDirectionResolved()
boolean isLayoutRequested()

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

boolean isLongClickable()

Indicates whether this view reacts to long click events or not.

boolean isNestedScrollingEnabled()

Returns true if nested scrolling is enabled for this view.

boolean isOpaque()

Indicates whether this View is opaque.

boolean isPaddingOffsetRequired()

If the View draws content inside its padding and enables fading edges, it needs to support padding offsets.

boolean isPaddingRelative()

Return if the padding has been set through relative values setPaddingRelative(int, int, int, int) or through

boolean isPivotSet()

Returns whether or not a pivot has been set by a call to setPivotX(float) or setPivotY(float).

final boolean isPreferKeepClear()

Retrieve the preference for this view to be kept clear.

boolean isPressed()

Indicates whether the view is currently in pressed state.

boolean isSaveEnabled()

Indicates whether this view will save its state (that is, whether its onSaveInstanceState() method will be called).

boolean isSaveFromParentEnabled()

Indicates whether the entire hierarchy under this view will save its state when a state saving traversal occurs from its parent.

boolean isScreenReaderFocusable()

Returns whether the view should be treated as a focusable unit by screen reader accessibility tools.

boolean isScrollContainer()

Indicates whether this view is one of the set of scrollable containers in its window.

boolean isScrollbarFadingEnabled()

Returns true if scrollbars will fade when this view is not scrolling

boolean isSelected()

Indicates the selection state of this view.

final boolean isShowingLayoutBounds()

Returns true when the View is attached and the system developer setting to show the layout bounds is enabled or false otherwise.

boolean isShown()

Returns the visibility of this view and all of its ancestors

boolean isSoundEffectsEnabled()
final boolean isTemporarilyDetached()

Tells whether the View is in the state between onStartTemporaryDetach() and onFinishTemporaryDetach().

boolean isTextAlignmentResolved()
boolean isTextDirectionResolved()
boolean isVerticalFadingEdgeEnabled()

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

boolean isVerticalScrollBarEnabled()

Indicate whether the vertical scrollbar should be drawn or not.

boolean isVisibleToUserForAutofill(int virtualId)

Computes whether this virtual autofill view is visible to the user.

void jumpDrawablesToCurrentState()

Call Drawable.jumpToCurrentState() on all Drawable objects associated with this view.

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)

Assign a size and position to a view and all of its descendants

This is the second phase of the layout mechanism.

final void measure(int widthMeasureSpec, int heightMeasureSpec)

This is called to find out how big a view should be.

static int[] mergeDrawableStates(int[] baseState, int[] additionalState)

Merge your own state values in additionalState into the base state values baseState that were returned by onCreateDrawableState(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.

void onAnimationEnd()

Invoked by a parent ViewGroup to notify the end of the animation currently associated with this view.

void onAnimationStart()

Invoked by a parent ViewGroup to notify the start of the animation currently associated with this view.

WindowInsets onApplyWindowInsets(WindowInsets insets)

Called when the view should apply WindowInsets according to its internal policy.

void onAttachedToWindow()

This is called when the view is attached to a window.

void onCancelPendingInputEvents()

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

boolean onCapturedPointerEvent(MotionEvent event)

Implement this method to handle captured pointer events

boolean onCheckIsTextEditor()

Check whether the called view is a text editor, in which case it would make sense to automatically display a soft input window for it.

void onConfigurationChanged(Configuration newConfig)

Called when the current configuration of the resources being used by the application have changed.

void onCreateContextMenu(ContextMenu menu)

Views should implement this if the view itself is going to add items to the context menu.

int[] onCreateDrawableState(int extraSpace)

Generate the new Drawable state for this view.

InputConnection onCreateInputConnection(EditorInfo outAttrs)

Create a new InputConnection for an InputMethod to interact with the view.

void onCreateViewTranslationRequest(int[] supportedFormats, Consumer<ViewTranslationRequest> requestsCollector)

Collects a ViewTranslationRequest which represents the content to be translated in the view.

void onCreateVirtualViewTranslationRequests(long[] virtualIds, int[] supportedFormats, Consumer<ViewTranslationRequest> requestsCollector)

Collects ViewTranslationRequests which represents the content to be translated for the virtual views in the host view.

void onDetachedFromWindow()

This is called when the view is detached from a window.

void onDisplayHint(int hint)

Gives this view a hint about whether is displayed or not.

boolean onDragEvent(DragEvent event)

Handles drag events sent by the system following a call to startDragAndDrop().

void onDraw(Canvas canvas)

Implement this to do your drawing.

void onDrawForeground(Canvas canvas)

Draw any foreground content for this view.

final void onDrawScrollBars(Canvas canvas)

Request the drawing of the horizontal and the vertical scrollbar.

boolean onFilterTouchEventForSecurity(MotionEvent event)

Filter the touch event to apply security policies.

void onFinishInflate()

Finalize inflating a view from XML.

void onFinishTemporaryDetach()

Called after onStartTemporaryDetach() when the container is done changing the view.

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.

void onInitializeAccessibilityEvent(AccessibilityEvent event)

Initializes an AccessibilityEvent with information about this View which is the event source.

void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info)

Initializes an AccessibilityNodeInfo with information about this view.

boolean onKeyDown(int keyCode, KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyDown(): perform press of the view when KeyEvent#KEYCODE_DPAD_CENTER or KeyEvent#KEYCODE_ENTER is released, if the view is enabled and clickable.

boolean onKeyLongPress(int keyCode, KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyLongPress(): always returns false (doesn't handle the event).

boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handle the event).

boolean onKeyPreIme(int keyCode, KeyEvent event)

Handle a key event before it is processed by any input method associated with the view hierarchy.

boolean onKeyShortcut(int keyCode, KeyEvent event)

Called on the focused view when a key shortcut event is not handled.

boolean onKeyUp(int keyCode, KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyUp(): perform clicking of the view when KeyEvent#KEYCODE_DPAD_CENTER, KeyEvent#KEYCODE_ENTER or KeyEvent#KEYCODE_SPACE is released.

void onLayout(boolean changed, int left, int top, int right, int bottom)

Called from layout when this view should assign a size and position to each of its children.

void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height.

void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY)

Called by overScrollBy(int, int, int, int, int, int, int, int, boolean) to respond to the results of an over-scroll operation.

void onPointerCaptureChange(boolean hasCapture)

Called when the window has just acquired or lost pointer capture.

void onPopulateAccessibilityEvent(AccessibilityEvent event)

Called from dispatchPopulateAccessibilityEvent(android.view.accessibility.AccessibilityEvent) giving a chance to this View to populate the accessibility event with its text content.

void onProvideAutofillStructure(ViewStructure structure, int flags)

Populates a ViewStructure to fullfil an autofill request.

void onProvideAutofillVirtualStructure(ViewStructure structure, int flags)

Populates a ViewStructure containing virtual children to fullfil an autofill request.

void onProvideContentCaptureStructure(ViewStructure structure, int flags)

Populates a ViewStructure for content capture.

void onProvideStructure(ViewStructure structure)

Called when assist structure is being retrieved from a view as part of Activity.onProvideAssistData.

void onProvideVirtualStructure(ViewStructure structure)

Called when assist structure is being retrieved from a view as part of Activity.onProvideAssistData to generate additional virtual structure under this view.

ContentInfo onReceiveContent(ContentInfo payload)

Implements the default behavior for receiving content for this type of view.

PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex)

Returns the pointer icon for the motion event, or null if it doesn't specify the icon.

void onRestoreInstanceState(Parcelable state)

Hook allowing a view to re-apply a representation of its internal state that had previously been generated by onSaveInstanceState().

void onRtlPropertiesChanged(int layoutDirection)

Called when any RTL property (layout direction or text direction or text alignment) has been changed.

Parcelable onSaveInstanceState()

Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state.

void onScreenStateChanged(int screenState)

This method is called whenever the state of the screen this view is attached to changes.

void onScrollCaptureSearch(Rect localVisibleRect, Point windowOffset, Consumer<ScrollCaptureTarget> targets)

Called when scroll capture is requested, to search for appropriate content to scroll.

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

boolean onSetAlpha(int alpha)

Invoked if there is a Transform that involves alpha.

void onSizeChanged(int w, int h, int oldw, int oldh)

This is called during layout when the size of this view has changed.

void onStartTemporaryDetach()

This is called when a container is going to temporarily detach a child, with ViewGroup.detachViewFromParent.

boolean onTouchEvent(MotionEvent event)

Implement this method to handle touch screen motion events.

boolean onTrackballEvent(MotionEvent event)

Implement this method to handle trackball motion events.

void onViewTranslationResponse(ViewTranslationResponse response)

Called when the content from View#onCreateViewTranslationRequest had been translated by the TranslationService.

void onVirtualViewTranslationResponses(LongSparseArray<ViewTranslationResponse> response)

Called when the content from View#onCreateVirtualViewTranslationRequests had been translated by the TranslationService.

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.

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.

void onWindowSystemUiVisibilityChanged(int visible)

This method was deprecated in API level 30. SystemUiVisibility flags are deprecated. Use WindowInsetsController instead.

void onWindowVisibilityChanged(int visibility)

Called when the window containing has change its visibility (between GONE, INVISIBLE, and VISIBLE).

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.

boolean performAccessibilityAction(int action, Bundle arguments)

Performs the specified accessibility action on the view.

boolean performClick()

Call this view's OnClickListener, if it is defined.

boolean performContextClick(float x, float y)

Call this view's OnContextClickListener, if it is defined.

boolean performContextClick()

Call this view's OnContextClickListener, if it is defined.

boolean performHapticFeedback(int feedbackConstant)

BZZZTT!!1!

Provide haptic feedback to the user for this view.

boolean performHapticFeedback(int feedbackConstant, int flags)

BZZZTT!!1!

Like performHapticFeedback(int), with additional options.

boolean performLongClick(float x, float y)

Calls this view's OnLongClickListener, if it is defined.

boolean performLongClick()

Calls this view's OnLongClickListener, if it is defined.

ContentInfo performReceiveContent(ContentInfo payload)

Receives the given content.

void playSoundEffect(int soundConstant)

Play a sound effect for this view.

boolean post(Runnable action)

Causes the Runnable to be added to the message queue.

boolean postDelayed(Runnable action, long delayMillis)

Causes the Runnable to be added to the message queue, to be run after the specified amount of time elapses.

void postInvalidate()

Cause an invalidate to happen on a subsequent cycle through the event loop.

void postInvalidate(int left, int top, int right, int bottom)

Cause an invalidate of the specified area to happen on a subsequent cycle through the event loop.

void postInvalidateDelayed(long delayMilliseconds, int left, int top, int right, int bottom)

Cause an invalidate of the specified area to happen on a subsequent cycle through the event loop.

void postInvalidateDelayed(long delayMilliseconds)

Cause an invalidate to happen on a subsequent cycle through the event loop.

void postInvalidateOnAnimation(int left, int top, int right, int bottom)

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

void postInvalidateOnAnimation()

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

void postOnAnimation(Runnable action)

Causes the Runnable to execute on the next animation time step.

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

Call this to force a view to update its drawable state.

void releasePointerCapture()

Releases the pointer capture.

boolean removeCallbacks(Runnable action)

Removes the specified Runnable from the message queue.

void removeOnAttachStateChangeListener(View.OnAttachStateChangeListener listener)

Remove a listener for attach state changes.

void removeOnLayoutChangeListener(View.OnLayoutChangeListener listener)

Remove a listener for layout changes.

void removeOnUnhandledKeyEventListener(View.OnUnhandledKeyEventListener listener)

Removes a listener which will receive unhandled KeyEvents.

void requestApplyInsets()

Ask that a new dispatch of onApplyWindowInsets(android.view.WindowInsets) be performed.

void requestFitSystemWindows()

This method was deprecated in API level 20. Use requestApplyInsets() for newer platform versions.

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.

final boolean requestFocus()

Call this to try to give focus to a specific view or to one of its descendants.

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.

final boolean requestFocusFromTouch()

Call this to try to give focus to a specific view or to one of its descendants.

void requestLayout()

Call this when something has changed which has invalidated the layout of this view.

void requestPointerCapture()

Requests pointer capture mode.

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 void requestUnbufferedDispatch(int source)

Request unbuffered dispatch of the given event source class to this view.

final void requestUnbufferedDispatch(MotionEvent event)

Request unbuffered dispatch of the given stream of MotionEvents to this View.

final <T extends View> T requireViewById(int id)

Finds the first descendant view with the given ID, the view itself if the ID matches getId(), or throws an IllegalArgumentException if the ID is invalid or there is no matching view in the hierarchy.

void resetPivot()

Clears any pivot previously set by a call to setPivotX(float) or setPivotY(float).

static int resolveSize(int size, int measureSpec)

Version of resolveSizeAndState(int, int, int) returning only the MEASURED_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 restoreDefaultFocus()

Gives focus to the default-focus view in the view hierarchy that has this view as a root.

void restoreHierarchyState(SparseArray<Parcelable> container)

Restore this view hierarchy's frozen state from the given container.

final void saveAttributeDataForStyleable(Context context, int[] styleable, AttributeSet attrs, TypedArray t, int defStyleAttr, int defStyleRes)

Stores debugging information about attributes.

void saveHierarchyState(SparseArray<Parcelable> container)

Store this view hierarchy's frozen state into the given container.

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 sendAccessibilityEvent(int eventType)

Sends an accessibility event of the given type.

void sendAccessibilityEventUnchecked(AccessibilityEvent event)

This method behaves exactly as sendAccessibilityEvent(int) but takes as an argument an empty AccessibilityEvent and does not perform a check whether accessibility is enabled.

void setAccessibilityDelegate(View.AccessibilityDelegate delegate)

Sets a delegate for implementing accessibility support via composition (as opposed to inheritance).

void setAccessibilityHeading(boolean isHeading)

Set if view is a heading for a section of content for accessibility purposes.

void setAccessibilityLiveRegion(int mode)

Sets the live region mode for this view.

void setAccessibilityPaneTitle(CharSequence accessibilityPaneTitle)

Visually distinct portion of a window with window-like semantics are considered panes for accessibility purposes.

void setAccessibilityTraversalAfter(int afterId)

Sets the id of a view after which this one is visited in accessibility traversal.

void setAccessibilityTraversalBefore(int beforeId)

Sets the id of a view before which this one is visited in accessibility traversal.

void setActivated(boolean activated)

Changes the activated state of this view.

void setAllowClickWhenDisabled(boolean clickableWhenDisabled)

Enables or disables click events for this view when disabled.

void setAlpha(float alpha)

Sets the opacity of the view to a value from 0 to 1, where 0 means the view is completely transparent and 1 means the view is completely opaque.

void setAnimation(Animation animation)

Sets the next animation to play for this view.

void setAnimationMatrix(Matrix matrix)

Changes the transformation matrix on the view.

void setAutoHandwritingEnabled(boolean enabled)

Set whether this view enables automatic handwriting initiation.

void setAutofillHints(String... autofillHints)

Sets the hints that help an AutofillService determine how to autofill the view with the user's data.

void setAutofillId(AutofillId id)

Sets the unique, logical identifier of this view in the activity, for autofill purposes.

void setBackground(Drawable background)

Set the background to a given Drawable, or remove the background.

void setBackgroundColor(int color)

Sets the background color for this view.

void setBackgroundDrawable(Drawable background)

This method was deprecated in API level 16. use setBackground(android.graphics.drawable.Drawable) instead

void setBackgroundResource(int resid)

Set the background to a given resource.

void setBackgroundTintBlendMode(BlendMode blendMode)

Specifies the blending mode used to apply the tint specified by setBackgroundTintList(android.content.res.ColorStateList)} to the background drawable.

void setBackgroundTintList(ColorStateList tint)

Applies a tint to the background drawable.

void setBackgroundTintMode(PorterDuff.Mode tintMode)

Specifies the blending mode used to apply the tint specified by setBackgroundTintList(android.content.res.ColorStateList)} to the background drawable.

final void setBottom(int bottom)

Sets the bottom position of this view relative to its parent.

void setCameraDistance(float distance)

Sets the distance along the Z axis (orthogonal to the X/Y plane on which views are drawn) from the camera to this view.

void setClickable(boolean clickable)

Enables or disables click events for this view.

void setClipBounds(Rect clipBounds)

Sets a rectangular area on this view to which the view will be clipped when it is drawn.

void setClipToOutline(boolean clipToOutline)

Sets whether the View's Outline should be used to clip the contents of the View.

void setContentCaptureSession(ContentCaptureSession contentCaptureSession)

Sets the (optional) ContentCaptureSession associated with this view.

void setContentDescription(CharSequence contentDescription)

Sets the View's content description.

void setContextClickable(boolean contextClickable)

Enables or disables context clicking for this view.

void setDefaultFocusHighlightEnabled(boolean defaultFocusHighlightEnabled)

Sets whether this View should use a default focus highlight when it gets focused but doesn't have R.attr.state_focused defined in its background.

void setDrawingCacheBackgroundColor(int color)

This method was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

void setDrawingCacheEnabled(boolean enabled)

This method was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

void setDrawingCacheQuality(int quality)

This method was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

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 setFadingEdgeLength(int length)

Set the size of the faded edge used to indicate that more content in this view is available.

void setFilterTouchesWhenObscured(boolean enabled)

Sets whether the framework should discard touches when the view's window is obscured by another visible window at the touched location.

void setFitsSystemWindows(boolean fitSystemWindows)

Sets whether or not this view should account for system screen decorations such as the status bar and inset its content; that is, controlling whether the default implementation of fitSystemWindows(android.graphics.Rect) will be executed.

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.

void setForceDarkAllowed(boolean allow)

Sets whether or not to allow force dark to apply to 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.

void setForegroundTintBlendMode(BlendMode blendMode)

Specifies the blending mode used to apply the tint specified by setForegroundTintList(android.content.res.ColorStateList)} to the background drawable.

void setForegroundTintList(ColorStateList tint)

Applies a tint to the foreground drawable.

void setForegroundTintMode(PorterDuff.Mode tintMode)

Specifies the blending mode used to apply the tint specified by setForegroundTintList(android.content.res.ColorStateList)} to the background drawable.

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 setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled)

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

void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled)

Define whether the horizontal scrollbar should be drawn or not.

void setHorizontalScrollbarThumbDrawable(Drawable drawable)

Defines the horizontal thumb drawable

void setHorizontalScrollbarTrackDrawable(Drawable drawable)

Defines the horizontal track drawable

void setHovered(boolean hovered)

Sets whether the view is currently hovered.

void setId(int id)

Sets the identifier for this view.

void setImportantForAccessibility(int mode)

Sets how to determine whether this view is important for accessibility which is if it fires accessibility events and if it is reported to accessibility services that query the screen.

void setImportantForAutofill(int mode)

Sets the mode for determining whether this view is considered important for autofill.

void setImportantForContentCapture(int mode)

Sets the mode for determining whether this view is considered important for content capture.

void setKeepScreenOn(boolean keepScreenOn)

Controls whether the screen should remain on, modifying the value of KEEP_SCREEN_ON.

void setKeyboardNavigationCluster(boolean isCluster)

Set whether this view is a root of a keyboard navigation cluster.

void setLabelFor(int id)

Sets the id of a view for which this view serves as a label for accessibility purposes.

void setLayerPaint(Paint paint)

Updates the Paint object used with the current layer (used only if the current layer type is not set to LAYER_TYPE_NONE).

void setLayerType(int layerType, Paint paint)

Specifies the type of layer backing this view.

void setLayoutDirection(int layoutDirection)

Set the layout direction for this view.

void setLayoutParams(ViewGroup.LayoutParams params)

Set the layout parameters associated with this view.

final void setLeft(int left)

Sets the left position of this view relative to its parent.

final void setLeftTopRightBottom(int left, int top, int right, int bottom)

Assign a size and position to this view.

void setLongClickable(boolean longClickable)

Enables or disables long click events for this view.

final void setMeasuredDimension(int measuredWidth, int measuredHeight)

This method must be called by onMeasure(int, int) to store the measured width and measured height.

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 is FOCUS_DOWN.

void setNextFocusForwardId(int nextFocusForwardId)

Sets the id of the view to use when the next focus is FOCUS_FORWARD.

void setNextFocusLeftId(int nextFocusLeftId)

Sets the id of the view to use when the next focus is FOCUS_LEFT.

void setNextFocusRightId(int nextFocusRightId)

Sets the id of the view to use when the next focus is FOCUS_RIGHT.

void setNextFocusUpId(int nextFocusUpId)

Sets the id of the view to use when the next focus is FOCUS_UP.

void setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener listener)

Set an OnApplyWindowInsetsListener to take over the policy for applying window insets to this view.

void setOnCapturedPointerListener(View.OnCapturedPointerListener l)

Set a listener to receive callbacks when the pointer capture state of a view changes.

void setOnClickListener(View.OnClickListener l)

Register a callback to be invoked when this view is clicked.

void setOnContextClickListener(View.OnContextClickListener l)

Register a callback to be invoked when this view is context clicked.

void setOnCreateContextMenuListener(View.OnCreateContextMenuListener l)

Register a callback to be invoked when the context menu for this view is being built.

void setOnDragListener(View.OnDragListener l)

Register a drag event listener callback object for this View.

void setOnFocusChangeListener(View.OnFocusChangeListener l)

Register a callback to be invoked when focus of this view changed.

void setOnGenericMotionListener(View.OnGenericMotionListener l)

Register a callback to be invoked when a generic motion event is sent to this view.

void setOnHoverListener(View.OnHoverListener l)

Register a callback to be invoked when a hover event is sent to this view.

void setOnKeyListener(View.OnKeyListener l)

Register a callback to be invoked when a hardware key is pressed in this view.

void setOnLongClickListener(View.OnLongClickListener l)

Register a callback to be invoked when this view is clicked and held.

void setOnReceiveContentListener(String[] mimeTypes, OnReceiveContentListener listener)

Sets the listener to be used to handle insertion of content into this view.

void setOnScrollChangeListener(View.OnScrollChangeListener l)

Register a callback to be invoked when the scroll X or Y positions of this view change.

void setOnSystemUiVisibilityChangeListener(View.OnSystemUiVisibilityChangeListener l)

This method was deprecated in API level 30. Use WindowInsets#isVisible(int) to find out about system bar visibilities by setting a OnApplyWindowInsetsListener on this view.

void setOnTouchListener(View.OnTouchListener l)

Register a callback to be invoked when a touch event is sent to this view.

void setOutlineAmbientShadowColor(int color)

Sets the color of the ambient shadow that is drawn when the view has a positive Z or elevation value.

void setOutlineProvider(ViewOutlineProvider provider)

Sets the ViewOutlineProvider of the view, which generates the Outline that defines the shape of the shadow it casts, and enables outline clipping.

void setOutlineSpotShadowColor(int color)

Sets the color of the spot shadow that is drawn when the view has a positive Z or elevation value.

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)

Sets the x location of the point around which the view is rotated and scaled.

void setPivotY(float pivotY)

Sets the y location of the point around which the view is rotated and scaled.

void setPointerIcon(PointerIcon pointerIcon)

Set the pointer icon for the current view.

final void setPreferKeepClear(boolean preferKeepClear)

Set a preference to keep the bounds of this view clear from floating windows above this view's window.

final void setPreferKeepClearRects(List<Rect> rects)

Set a preference to keep the provided rects clear from floating windows above this view's window.

void setPressed(boolean pressed)

Sets the pressed state for this view.

void setRenderEffect(RenderEffect renderEffect)

Configure the RenderEffect to apply to 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 setSaveEnabled(boolean enabled)

Controls whether the saving of this view's state is enabled (that is, whether its onSaveInstanceState() method will be called).

void setSaveFromParentEnabled(boolean enabled)

Controls whether the entire hierarchy under this view will save its state when a state saving traversal occurs from its parent.

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 setScreenReaderFocusable(boolean screenReaderFocusable)

Sets whether this View should be a focusable element for screen readers and include non-focusable Views from its subtree when providing feedback.

void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade)

Define the delay before scrollbars fade.

void setScrollBarFadeDuration(int scrollBarFadeDuration)

Define the scrollbar fade duration.

void setScrollBarSize(int scrollBarSize)

Define the scrollbar size.

void setScrollBarStyle(int style)

Specify the style of the scrollbars.

final void setScrollCaptureCallback(ScrollCaptureCallback callback)

Sets the callback to receive scroll capture requests.

void setScrollCaptureHint(int hint)

Sets the scroll capture hint for this View.

void setScrollContainer(boolean isScrollContainer)

Change whether this view is one of the set of scrollable containers in its window.

void setScrollIndicators(int indicators, int mask)

Sets the state of the scroll indicators specified by the mask.

void setScrollIndicators(int indicators)

Sets the state of all scroll indicators.

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 setScrollbarFadingEnabled(boolean fadeScrollbars)

Define whether scrollbars will fade when the view is not scrolling.

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 setStateDescription(CharSequence stateDescription)

Sets the View's state description.

void setStateListAnimator(StateListAnimator stateListAnimator)

Attaches the provided StateListAnimator to this View.

void setSystemGestureExclusionRects(List<Rect> rects)

Sets a list of areas within this view's post-layout coordinate space where the system should not intercept touch or other pointing device gestures.

void setSystemUiVisibility(int visibility)

This method was deprecated in API level 30. SystemUiVisibility flags are deprecated. Use WindowInsetsController instead.

void setTag(int key, Object tag)

Sets a tag associated with this view and a key.

void setTag(Object tag)

Sets the tag associated with this view.

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.

void setTouchDelegate(TouchDelegate delegate)

Sets the TouchDelegate for this View.

void setTransitionAlpha(float alpha)

This property is intended only for use by the Fade transition, which animates it to produce a visual translucency that does not side-effect (or get affected by) the real alpha property.

final void setTransitionName(String transitionName)

Sets the name of the View to be used to identify Views in Transitions.

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 its left position.

void setTranslationY(float translationY)

Sets the vertical location of this view relative to its top position.

void setTranslationZ(float translationZ)

Sets the depth location of this view relative to its elevation.

void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled)

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

void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled)

Define whether the vertical scrollbar should be drawn or not.

void setVerticalScrollbarPosition(int position)

Set the position of the vertical scroll bar.

void setVerticalScrollbarThumbDrawable(Drawable drawable)

Defines the vertical scrollbar thumb drawable

void setVerticalScrollbarTrackDrawable(Drawable drawable)

Defines the vertical scrollbar track drawable

void setViewTranslationCallback(ViewTranslationCallback callback)

Sets a ViewTranslationCallback that is used to display/hide the translated information.

void setVisibility(int visibility)

Set the visibility state of this view.

void setWillNotCacheDrawing(boolean willNotCacheDrawing)

This method was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

void setWillNotDraw(boolean willNotDraw)

If this view doesn't do any drawing on its own, set this flag to allow further optimizations.

void setWindowInsetsAnimationCallback(WindowInsetsAnimation.Callback callback)

Sets a WindowInsetsAnimation.Callback to be notified about animations of windows that cause insets.

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.

boolean showContextMenu()

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.

ActionMode startActionMode(ActionMode.Callback callback, int type)

Start an action mode with the given type.

ActionMode startActionMode(ActionMode.Callback callback)

Start an action mode with the default type ActionMode#TYPE_PRIMARY.

void startAnimation(Animation animation)

Start the specified animation now.

final boolean startDrag(ClipData data, View.DragShadowBuilder shadowBuilder, Object myLocalState, int flags)

This method was deprecated in API level 24. Use startDragAndDrop() for newer platform versions.

final boolean startDragAndDrop(ClipData data, View.DragShadowBuilder shadowBuilder, Object myLocalState, int flags)

Starts a drag and drop operation.

boolean startNestedScroll(int axes)

Begin a nestable scroll operation along the given axes.

void stopNestedScroll()

Stop a nested scroll in progress.

String toString()

Returns a string representation of the object.

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.

void unscheduleDrawable(Drawable who, Runnable what)

Cancels a scheduled action on a drawable.

void unscheduleDrawable(Drawable who)

Unschedule any events associated with the given Drawable.

final void updateDragShadow(View.DragShadowBuilder shadowBuilder)

Updates the drag shadow for the ongoing drag and drop operation.

boolean verifyDrawable(Drawable who)

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

This method was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

boolean willNotDraw()

Returns whether or not this View draws on its own.

From class java.lang.Object

Object clone()

Creates and returns a copy of this object.

boolean equals(Object obj)

Indicates whether some other object is "equal to" this one.

void finalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

final Class<?> getClass()

Returns the runtime class of this Object.

int hashCode()

Returns a hash code value for the object.

final void notify()

Wakes up a single thread that is waiting on this object's monitor.

final void notifyAll()

Wakes up all threads that are waiting on this object's monitor.

String toString()

Returns a string representation of the object.

final void wait(long timeout, int nanos)

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

final void wait(long timeout)

Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

final void wait()

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

From interface android.graphics.drawable.Drawable.Callback

abstract void invalidateDrawable(Drawable who)

Called when the drawable needs to be redrawn.

abstract void scheduleDrawable(Drawable who, Runnable what, long when)

A Drawable can call this to schedule the next frame of its animation.

abstract void unscheduleDrawable(Drawable who, Runnable what)

A Drawable can call this to unschedule an action previously scheduled with scheduleDrawable(Drawable, Runnable, long).

From interface android.view.KeyEvent.Callback

abstract boolean onKeyDown(int keyCode, KeyEvent event)

Called when a key down event has occurred.

abstract boolean onKeyLongPress(int keyCode, KeyEvent event)

Called when a long press has occurred.

abstract boolean onKeyMultiple(int keyCode, int count, KeyEvent event)

Called when a user's interaction with an analog control, such as flinging a trackball, generates simulated down/up events for the same key multiple times in quick succession.

abstract boolean onKeyUp(int keyCode, KeyEvent event)

Called when a key up event has occurred.

From interface android.view.accessibility.AccessibilityEventSource

abstract void sendAccessibilityEvent(int eventType)

Handles the request for sending an AccessibilityEvent given the event type.

abstract void sendAccessibilityEventUnchecked(AccessibilityEvent event)

Handles the request for sending an AccessibilityEvent.

From interface android.view.ViewTreeObserver.OnPreDrawListener

abstract boolean onPreDraw()

Callback method to be invoked when the view tree is about to be drawn.

XML attributes

android:allowUndo

Whether undo should be allowed for editable text. Defaults to true.

May be a boolean value, such as "true" or "false".

Controls whether links such as urls and email addresses are automatically found and converted to clickable links. The default value is "none", disabling this feature.

Must be one or more (separated by '|') of the following constant values.

ConstantValueDescription
all f Match all patterns (equivalent to web|email|phone|map).
email 2 Match email addresses.
map 8 Match map addresses. Deprecated: see Linkify.MAP_ADDRESSES.
none 0 Match no patterns (default).
phone 4 Match phone numbers.
web 1 Match Web URLs.

Related methods:

  • setAutoLinkMask(int)

android:autoSizeMaxTextSize

The maximum text size constraint to be used when auto-sizing text.

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

Related methods:

  • setAutoSizeTextTypeUniformWithConfiguration(int,int,int,int)

android:autoSizeMinTextSize

The minimum text size constraint to be used when auto-sizing text.

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

Related methods:

  • setAutoSizeTextTypeUniformWithConfiguration(int,int,int,int)

android:autoSizePresetSizes

Resource array of dimensions to be used in conjunction with autoSizeTextType set to uniform. Overrides autoSizeStepGranularity if set.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character;

May be an integer value, such as "100".

May be a boolean value, such as "true" or "false".

May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

May be a floating point value, such as "1.2".

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

May be a fractional value, which is a floating point number appended with either % or %p, such as "14.5%". The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to some parent container.

Related methods:

  • setAutoSizeTextTypeUniformWithPresetSizes(int,int)

android:autoSizeStepGranularity

Specify the auto-size step size if autoSizeTextType is set to uniform. The default is 1px. Overwrites autoSizePresetSizes if set.

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

Related methods:

  • setAutoSizeTextTypeUniformWithConfiguration(int,int,int,int)

android:autoSizeTextType

Specify the type of auto-size. Note that this feature is not supported by EditText, works only for TextView.

Must be one of the following constant values.

ConstantValueDescription
none 0 No auto-sizing (default).
uniform 1 Uniform horizontal and vertical text size scaling to fit within the container.

Related methods:

  • setAutoSizeTextTypeWithDefaults(int)

android:autoText

If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors. The default is "false".

May be a boolean value, such as "true" or "false".

Related methods:

  • setKeyListener(KeyListener)

android:breakStrategy

Break strategy (control over paragraph layout).

Must be one of the following constant values.

ConstantValueDescription
balanced 2 Line breaking strategy balances line lengths.
high_quality 1 Line breaking uses high-quality strategy, including hyphenation.
simple 0 Line breaking uses simple strategy.

Related methods:

  • setBreakStrategy(int)

android:bufferType

Determines the minimum type that getText() will return. The default is "normal". Note that EditText and LogTextBox always return Editable, even if you specify something less powerful here.

Must be one of the following constant values.

ConstantValueDescription
editable 2 Can only return Spannable and Editable.
normal 0 Can return any CharSequence, possibly a Spanned one if the source text was Spanned.
spannable 1 Can only return Spannable.

Related methods:

  • setText(int,TextView.BufferType)

android:capitalize

If set, specifies that this TextView has a textual input method and should automatically capitalize what the user types. The default is "none".

Must be one of the following constant values.

ConstantValueDescription
characters 3 Capitalize every character.
none 0 Don't automatically capitalize anything.
sentences 1 Capitalize the first word of each sentence.
words 2 Capitalize the first letter of every word.

Related methods:

  • setKeyListener(KeyListener)

android:cursorVisible

Makes the cursor visible (the default) or invisible.

May be a boolean value, such as "true" or "false".

Related methods:

  • setCursorVisible(boolean)

android:digits

If set, specifies that this TextView has a numeric input method and that these specific characters are the ones that it will accept. If this is set, numeric is implied to be true. The default is false.

May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character;

Related methods:

  • setKeyListener(KeyListener)

android:drawableBottom

The drawable to be drawn below the text.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

Related methods:

  • setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)

android:drawableEnd

The drawable to be drawn to the end of the text.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

Related methods:

  • setCompoundDrawablesRelativeWithIntrinsicBounds(int,int,int,int)

android:drawableLeft

The drawable to be drawn to the left of the text.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

Related methods:

  • setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)

android:drawablePadding

The padding between the drawables and the text.

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

Related methods:

  • setCompoundDrawablePadding(int)

android:drawableRight

The drawable to be drawn to the right of the text.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

Related methods:

  • setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)

android:drawableStart

The drawable to be drawn to the start of the text.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

Related methods:

  • setCompoundDrawablesRelativeWithIntrinsicBounds(int,int,int,int)

android:drawableTint

Tint to apply to the compound (left, top, etc.) drawables.

May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

Related methods:

  • setCompoundDrawableTintList(ColorStateList)

android:drawableTintMode

Blending mode used to apply the compound (left, top, etc.) drawables tint.

Must be one of the following constant values.

ConstantValueDescription
add 10 Combines the tint and drawable color and alpha channels, clamping the result to valid color values. Saturate(S + D)
multiply e Multiplies the color and alpha channels of the drawable with those of the tint. [Sa * Da, Sc * Dc]
screen f [Sa + Da - Sa * Da, Sc + Dc - Sc * Dc]
src_atop 9 The tint is drawn above the drawable, but with the drawable’s alpha channel masking the result. [Da, Sc * Da + (1 - Sa) * Dc]
src_in 5 The tint is masked by the alpha channel of the drawable. The drawable’s color channels are thrown out. [Sa * Da, Sc * Da]
src_over 3 The tint is drawn on top of the drawable. [Sa + (1 - Sa)*Da, Rc = Sc + (1 - Sa)*Dc]

Related methods:

  • setCompoundDrawableTintMode(PorterDuff.Mode)

android:drawableTop

The drawable to be drawn above the text.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

Related methods:

  • setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)

android:editable

If set, specifies that this TextView has an input method. It will be a textual one unless it has otherwise been specified. For TextView, this is false by default. For EditText, it is true by default.

May be a boolean value, such as "true" or "false".

android:editorExtras

Reference to an <input-extras> XML resource containing additional data to supply to an input method, which is private to the implementation of the input method. This simply fills in the EditorInfo.extras field when the input method is connected.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

Related methods:

  • setInputExtras(int)

android:elegantTextHeight

Elegant text height, especially for less compacted complex script text.

May be a boolean value, such as "true" or "false".

Related methods:

  • setElegantTextHeight(boolean)

android:ellipsize

If set, causes words that are longer than the view is wide to be ellipsized instead of broken in the middle. You will often also want to set scrollHorizontally or singleLine as well so that the text as a whole is also constrained to a single line instead of still allowed to be broken onto multiple lines.

Must be one of the following constant values.

ConstantValueDescription
end 3
marquee 4
middle 2
none 0
start 1

Related methods:

  • setEllipsize(TextUtils.TruncateAt)

android:ems

Makes the TextView be exactly this many ems wide.

May be an integer value, such as "100".

Related methods:

  • setEms(int)

android:enabled

Specifies whether the widget is enabled. The interpretation of the enabled state varies by subclass. For example, a non-enabled EditText prevents the user from editing the contained text, and a non-enabled Button prevents the user from tapping the button. The appearance of enabled and non-enabled widgets may differ, if the drawables referenced from evaluating state_enabled differ.

May be a boolean value, such as "true" or "false".

android:fallbackLineSpacing

Whether to respect the ascent and descent of the fallback fonts that are used in displaying the text. When true, fallback fonts that end up getting used can increase the ascent and descent of the lines that they are used on.

May be a boolean value, such as "true" or "false".

Related methods:

  • setFallbackLineSpacing(boolean)

android:firstBaselineToTopHeight

Distance from the top of the TextView to the first text baseline. If set, this overrides the value set for paddingTop.

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

Related methods:

  • setFirstBaselineToTopHeight(int)

android:fontFamily

Font family (named by string or as a font resource reference) for the text.

May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character;

Related methods:

  • setTypeface(Typeface)

android:fontFeatureSettings

Font feature settings.

May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character;

Related methods:

  • setFontFeatureSettings(String)

android:fontVariationSettings

Font variation settings.

May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character;

Related methods:

  • setFontVariationSettings(String)

android:freezesText

If set, the text view will include its current complete text inside of its frozen icicle in addition to meta-data such as the current cursor position. By default this is disabled; it can be useful when the contents of a text view is not stored in a persistent place such as a content provider. For EditText it is always enabled, regardless of the value of the attribute.

May be a boolean value, such as "true" or "false".

Related methods:

  • setFreezesText(boolean)

android:gravity

Specifies how to align the text by the view's x- and/or y-axis when the text is smaller than the view.

Must be one or more (separated by '|') of the following constant values.

ConstantValueDescription
bottom 50 Push object to the bottom of its container, not changing its size.
center 11 Place the object in the center of its container in both the vertical and horizontal axis, not changing its size.
center_horizontal 1 Place object in the horizontal center of its container, not changing its size.
center_vertical 10 Place object in the vertical center of its container, not changing its size.
clip_horizontal 8 Additional option that can be set to have the left and/or right edges of the child clipped to its container's bounds. The clip will be based on the horizontal gravity: a left gravity will clip the right edge, a right gravity will clip the left edge, and neither will clip both edges.
clip_vertical 80 Additional option that can be set to have the top and/or bottom edges of the child clipped to its container's bounds. The clip will be based on the vertical gravity: a top gravity will clip the bottom edge, a bottom gravity will clip the top edge, and neither will clip both edges.
end 800005 Push object to the end of its container, not changing its size.
fill 77 Grow the horizontal and vertical size of the object if needed so it completely fills its container.
fill_horizontal 7 Grow the horizontal size of the object if needed so it completely fills its container.
fill_vertical 70 Grow the vertical size of the object if needed so it completely fills its container.
left 3 Push object to the left of its container, not changing its size.
right 5 Push object to the right of its container, not changing its size.
start 800003 Push object to the beginning of its container, not changing its size.
top 30 Push object to the top of its container, not changing its size.

Related methods:

  • setGravity(int)

android:height

Makes the TextView be exactly this tall. You could get the same effect by specifying this number in the layout parameters.

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

Related methods:

  • setHeight(int)

android:hint

Hint text to display when the text is empty.

May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character;

Related methods:

  • setHint(int)

android:hyphenationFrequency

Frequency of automatic hyphenation.

Must be one of the following constant values.

ConstantValueDescription
full 2 Standard amount of hyphenation, useful for running text and for screens with limited space for text.
fullFast 4 Same to hyphenationFrequency="full" but using faster algorithm for measuring hyphenation break points. To make text rendering faster with hyphenation, this algorithm ignores some hyphen character related typographic features, e.g. kerning.
none 0 No hyphenation.
normal 1 Less frequent hyphenation, useful for informal use cases, such as chat messages.
normalFast 3 Same to hyphenationFrequency="normal" but using faster algorithm for measuring hyphenation break points. To make text rendering faster with hyphenation, this algorithm ignores some hyphen character related typographic features, e.g. kerning.

Related methods:

  • setHyphenationFrequency(int)

android:imeActionId

Supply a value for EditorInfo.actionId used when an input method is connected to the text view.

May be an integer value, such as "100".

Related methods:

  • setImeActionLabel(CharSequence,int)

android:imeActionLabel

Supply a value for EditorInfo.actionLabel used when an input method is connected to the text view.

May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character;

Related methods:

  • setImeActionLabel(CharSequence,int)

android:imeOptions

Additional features you can enable in an IME associated with an editor to improve the integration with your application. The constants here correspond to those defined by EditorInfo.imeOptions.

Must be one or more (separated by '|') of the following constant values.

ConstantValueDescription
actionDone 6 The action key performs a "done" operation, closing the soft input method. Corresponds to EditorInfo.IME_ACTION_DONE.
actionGo 2 The action key performs a "go" operation to take the user to the target of the text they typed. Typically used, for example, when entering a URL. Corresponds to EditorInfo.IME_ACTION_GO.
actionNext 5 The action key performs a "next" operation, taking the user to the next field that will accept text. Corresponds to EditorInfo.IME_ACTION_NEXT.
actionNone 1 This editor has no action associated with it. Corresponds to EditorInfo.IME_ACTION_NONE.
actionPrevious 7 The action key performs a "previous" operation, taking the user to the previous field that will accept text. Corresponds to EditorInfo.IME_ACTION_PREVIOUS.
actionSearch 3 The action key performs a "search" operation, taking the user to the results of searching for the text the have typed (in whatever context is appropriate). Corresponds to EditorInfo.IME_ACTION_SEARCH.
actionSend 4 The action key performs a "send" operation, delivering the text to its target. This is typically used when composing a message. Corresponds to EditorInfo.IME_ACTION_SEND.
actionUnspecified 0 There is no specific action associated with this editor, let the editor come up with its own if it can. Corresponds to EditorInfo.IME_NULL.
flagForceAscii 80000000 Used to request that the IME should be capable of inputting ASCII characters. The intention of this flag is to ensure that the user can type Roman alphabet characters in a TextView used for, typically, account ID or password input. It is expected that IMEs normally are able to input ASCII even without being told so (such IMEs already respect this flag in a sense), but there could be some cases they aren't when, for instance, only non-ASCII input languages like Arabic, Greek, Hebrew, Russian are enabled in the IME. Applications need to be aware that the flag is not a guarantee, and not all IMEs will respect it. However, it is strongly recommended for IME authors to respect this flag especially when their IME could end up with a state that has only non-ASCII input languages enabled.

Corresponds to EditorInfo.IME_FLAG_FORCE_ASCII.

flagNavigateNext 8000000 Used to specify that there is something interesting that a forward navigation can focus on. This is like using actionNext, except allows the IME to be multiline (with an enter key) as well as provide forward navigation. Note that some IMEs may not be able to do this, especially when running on a small screen where there is little space. In that case it does not need to present a UI for this option. Like actionNext, if the user selects the IME's facility to forward navigate, this will show up in the application at InputConnection.performEditorAction(int).

Corresponds to EditorInfo.IME_FLAG_NAVIGATE_NEXT.

flagNavigatePrevious 4000000 Like flagNavigateNext, but specifies there is something interesting that a backward navigation can focus on. If the user selects the IME's facility to backward navigate, this will show up in the application as an actionPrevious at InputConnection.performEditorAction(int).

Corresponds to EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS.

flagNoAccessoryAction 20000000 Used in conjunction with a custom action, this indicates that the action should not be available as an accessory button when the input method is full-screen. Note that by setting this flag, there can be cases where the action is simply never available to the user. Setting this generally means that you think showing text being edited is more important than the action you have supplied.

Corresponds to EditorInfo.IME_FLAG_NO_ACCESSORY_ACTION.

flagNoEnterAction 40000000 Used in conjunction with a custom action, this indicates that the action should not be available in-line as a replacement for the "enter" key. Typically this is because the action has such a significant impact or is not recoverable enough that accidentally hitting it should be avoided, such as sending a message. Note that TextView will automatically set this flag for you on multi-line text views.

Corresponds to EditorInfo.IME_FLAG_NO_ENTER_ACTION.

flagNoExtractUi 10000000 Used to specify that the IME does not need to show its extracted text UI. For input methods that may be fullscreen, often when in landscape mode, this allows them to be smaller and let part of the application be shown behind. Though there will likely be limited access to the application available from the user, it can make the experience of a (mostly) fullscreen IME less jarring. Note that when this flag is specified the IME may not be set up to be able to display text, so it should only be used in situations where this is not needed.

Corresponds to EditorInfo.IME_FLAG_NO_EXTRACT_UI.

flagNoFullscreen 2000000 Used to request that the IME never go into fullscreen mode. Applications need to be aware that the flag is not a guarantee, and not all IMEs will respect it.

Corresponds to EditorInfo.IME_FLAG_NO_FULLSCREEN.

flagNoPersonalizedLearning 1000000 Used to request that the IME should not update any personalized data such as typing history and personalized language model based on what the user typed on this text editing object. Typical use cases are:
  • When the application is in a special mode, where user's activities are expected to be not recorded in the application's history. Some web browsers and chat applications may have this kind of modes.
  • When storing typing history does not make much sense. Specifying this flag in typing games may help to avoid typing history from being filled up with words that the user is less likely to type in their daily life. Another example is that when the application already knows that the expected input is not a valid word (e.g. a promotion code that is not a valid word in any natural language).

Applications need to be aware that the flag is not a guarantee, and some IMEs may not respect it.

normal 0 There are no special semantics associated with this editor.

Related methods:

  • setImeOptions(int)

android:includeFontPadding

Leave enough room for ascenders and descenders instead of using the font ascent and descent strictly. (Normally true).

May be a boolean value, such as "true" or "false".

Related methods:

  • setIncludeFontPadding(boolean)

android:inputMethod

If set, specifies that this TextView should use the specified input method (specified by fully-qualified class name).

May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character;

Related methods:

  • setKeyListener(KeyListener)

android:inputType

The type of data being placed in a text field, used to help an input method decide how to let the user enter text. The constants here correspond to those defined by InputType. Generally you can select a single value, though some can be combined together as indicated. Setting this attribute to anything besides none also implies that the text is editable.

Must be one or more (separated by '|') of the following constant values.

ConstantValueDescription
date 14 For entering a date. Corresponds to InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_DATE.
datetime 4 For entering a date and time. Corresponds to InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_NORMAL.
none 0 There is no content type. The text is not editable.
number 2 A numeric only field. Corresponds to InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL.
numberDecimal 2002 Can be combined with number and its other options to allow a decimal (fractional) number. Corresponds to InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL.
numberPassword 12 A numeric password field. Corresponds to InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD.
numberSigned 1002 Can be combined with number and its other options to allow a signed number. Corresponds to InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED.
phone 3 For entering a phone number. Corresponds to InputType.TYPE_CLASS_PHONE.
text 1 Just plain old text. Corresponds to InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL.
textAutoComplete 10001 Can be combined with text and its variations to specify that this field will be doing its own auto-completion and talking with the input method appropriately. Corresponds to InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE.
textAutoCorrect 8001 Can be combined with text and its variations to request auto-correction of text being input. Corresponds to InputType.TYPE_TEXT_FLAG_AUTO_CORRECT.
textCapCharacters 1001 Can be combined with text and its variations to request capitalization of all characters. Corresponds to InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS.
textCapSentences 4001 Can be combined with text and its variations to request capitalization of the first character of every sentence. Corresponds to InputType.TYPE_TEXT_FLAG_CAP_SENTENCES.
textCapWords 2001 Can be combined with text and its variations to request capitalization of the first character of every word. Corresponds to InputType.TYPE_TEXT_FLAG_CAP_WORDS.
textEmailAddress 21 Text that will be used as an e-mail address. Corresponds to InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS.
textEmailSubject 31 Text that is being supplied as the subject of an e-mail. Corresponds to InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_SUBJECT.
textEnableTextConversionSuggestions 100001 Can be combined with text and its variations to indicate that if there is extra information, the IME should provide TextAttribute. Corresponds to InputType.TYPE_TEXT_FLAG_ENABLE_TEXT_CONVERSION_SUGGESTIONS.
textFilter b1 Text that is filtering some other data. Corresponds to InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_FILTER.
textImeMultiLine 40001 Can be combined with text and its variations to indicate that though the regular text view should not be multiple lines, the IME should provide multiple lines if it can. Corresponds to InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE.
textLongMessage 51 Text that is the content of a long message. Corresponds to InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE.
textMultiLine 20001 Can be combined with text and its variations to allow multiple lines of text in the field. If this flag is not set, the text field will be constrained to a single line. Corresponds to InputType.TYPE_TEXT_FLAG_MULTI_LINE. Note: If this flag is not set and the text field doesn't have max length limit, the framework automatically set maximum length of the characters to 5000 for the performance reasons.
textNoSuggestions 80001 Can be combined with text and its variations to indicate that the IME should not show any dictionary-based word suggestions. Corresponds to InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS.
textPassword 81 Text that is a password. Corresponds to InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD.
textPersonName 61 Text that is the name of a person. Corresponds to InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PERSON_NAME.
textPhonetic c1 Text that is for phonetic pronunciation, such as a phonetic name field in a contact entry. Corresponds to InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PHONETIC.
textPostalAddress 71 Text that is being supplied as a postal mailing address. Corresponds to InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS.
textShortMessage 41 Text that is the content of a short message. Corresponds to InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE.
textUri 11 Text that will be used as a URI. Corresponds to InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI.
textVisiblePassword 91 Text that is a password that should be visible. Corresponds to InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD.
textWebEditText a1 Text that is being supplied as text in a web form. Corresponds to InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT.
textWebEmailAddress d1 Text that will be used as an e-mail address on a web form. Corresponds to InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS.
textWebPassword e1 Text that will be used as a password on a web form. Corresponds to InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD.
time 24 For entering a time. Corresponds to InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_TIME.

Related methods:

  • setRawInputType(int)

android:justificationMode

Mode for justification.

Must be one of the following constant values.

ConstantValueDescription
inter_word 1 Justification by stretching word spacing.
none 0 No justification.

android:lastBaselineToBottomHeight

Distance from the bottom of the TextView to the last text baseline. If set, this overrides the value set for paddingBottom.

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

Related methods:

  • setLastBaselineToBottomHeight(int)

android:letterSpacing

Text letter-spacing.

May be a floating point value, such as "1.2".

Related methods:

  • setLetterSpacing(float)

android:lineBreakStyle

Specifies the line-break strategies for text wrapping.

Must be one of the following constant values.

ConstantValueDescription
loose 1 The least restrictive line-break rules are used for line breaking.
none 0 No line-break rules are used for line breaking.
normal 2 The most common line-break rules are used for line breaking.
strict 3 The most strict line-break rules are used for line breaking.

android:lineBreakWordStyle

Specifies the line-break word strategies for text wrapping.

Must be one of the following constant values.

ConstantValueDescription
none 0 No line-break word style is used for line breaking.
phrase 1 Line breaking is based on phrases, which results in text wrapping only on meaningful words.

android:lineHeight

Explicit height between lines of text. If set, this will override the values set for lineSpacingExtra and lineSpacingMultiplier.

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

Related methods:

  • setLineHeight(int)

android:lineSpacingExtra

Extra spacing between lines of text. The value will not be applied for the last line of text.

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

Related methods:

  • setLineSpacing(float,float)

android:lineSpacingMultiplier

Extra spacing between lines of text, as a multiplier. The value will not be applied for the last line of text.

May be a floating point value, such as "1.2".

Related methods:

  • setLineSpacing(float,float)

android:lines

Makes the TextView be exactly this many lines tall.

May be an integer value, such as "100".

Related methods:

  • setLines(int)

android:linksClickable

If set to false, keeps the movement method from being set to the link movement method even if autoLink causes links to be found.

May be a boolean value, such as "true" or "false".

Related methods:

  • setLinksClickable(boolean)

android:marqueeRepeatLimit

The number of times to repeat the marquee animation. Only applied if the TextView has marquee enabled.

May be an integer value, such as "100".

Must be one of the following constant values.

ConstantValueDescription
marquee_forever ffffffff Indicates that marquee should repeat indefinitely.

Related methods:

  • setMarqueeRepeatLimit(int)

android:maxEms

Makes the TextView be at most this many ems wide.

May be an integer value, such as "100".

Related methods:

  • setMaxEms(int)

android:maxHeight

Makes the TextView be at most this many pixels tall.

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

Related methods:

  • setMaxHeight(int)

android:maxLength

Set an input filter to constrain the text length to the specified number.

May be an integer value, such as "100".

Related methods:

  • setFilters(InputFilter)

android:maxLines

Makes the TextView be at most this many lines tall. When used on an editable text, the inputType attribute's value must be combined with the textMultiLine flag for the maxLines attribute to apply.

May be an integer value, such as "100".

Related methods:

  • setMaxLines(int)

android:maxWidth

Makes the TextView be at most this many pixels wide.

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

Related methods:

  • setMaxWidth(int)

android:minEms

Makes the TextView be at least this many ems wide.

May be an integer value, such as "100".

Related methods:

  • setMinEms(int)

android:minHeight

Makes the TextView be at least this many pixels tall.

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

Related methods:

  • setMinHeight(int)

android:minLines

Makes the TextView be at least this many lines tall. When used on an editable text, the inputType attribute's value must be combined with the textMultiLine flag for the minLines attribute to apply.

May be an integer value, such as "100".

Related methods:

  • setMinLines(int)

android:minWidth

Makes the TextView be at least this many pixels wide.

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

Related methods:

  • setMinWidth(int)

android:numeric

If set, specifies that this TextView has a numeric input method. The default is false.

Must be one or more (separated by '|') of the following constant values.

ConstantValueDescription
decimal 5 Input is numeric, with decimals allowed.
integer 1 Input is numeric.
signed 3 Input is numeric, with sign allowed.

Related methods:

  • setKeyListener(KeyListener)

android:password

Whether the characters of the field are displayed as password dots instead of themselves.

May be a boolean value, such as "true" or "false".

Related methods:

  • setTransformationMethod(TransformationMethod)

android:phoneNumber

If set, specifies that this TextView has a phone number input method. The default is false.

May be a boolean value, such as "true" or "false".

Related methods:

  • setKeyListener(KeyListener)

android:privateImeOptions

An addition content type description to supply to the input method attached to the text view, which is private to the implementation of the input method. This simply fills in the EditorInfo.privateImeOptions field when the input method is connected.

May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character;

Related methods:

  • setPrivateImeOptions(String)

android:scrollHorizontally

Whether the text is allowed to be wider than the view (and therefore can be scrolled horizontally).

May be a boolean value, such as "true" or "false".

Related methods:

  • setHorizontallyScrolling(boolean)

android:selectAllOnFocus

If the text is selectable, select it all when the view takes focus.

May be a boolean value, such as "true" or "false".

Related methods:

  • setSelectAllOnFocus(boolean)

android:shadowColor

Place a blurred shadow of text underneath the text, drawn with the specified color. The text shadow produced does not interact with properties on View that are responsible for real time shadows, elevation and translationZ.

May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

Related methods:

  • setShadowLayer(float,float,float,int)

android:shadowDx

Horizontal offset of the text shadow.

May be a floating point value, such as "1.2".

Related methods:

  • setShadowLayer(float,float,float,int)

android:shadowDy

Vertical offset of the text shadow.

May be a floating point value, such as "1.2".

Related methods:

  • setShadowLayer(float,float,float,int)

android:shadowRadius

Blur radius of the text shadow.

May be a floating point value, such as "1.2".

Related methods:

  • setShadowLayer(float,float,float,int)

android:singleLine

Constrains the text to a single horizontally scrolling line instead of letting it wrap onto multiple lines, and advances focus instead of inserting a newline when you press the enter key. The default value is false (multi-line wrapped text mode) for non-editable text, but if you specify any value for inputType, the default is true (single-line input field mode).

May be a boolean value, such as "true" or "false".

Related methods:

  • setTransformationMethod(TransformationMethod)

android:text

Text to display.

May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character;

Related methods:

  • setText(int,TextView.BufferType)

android:textAllCaps

Present the text in ALL CAPS. This may use a small-caps form when available.

May be a boolean value, such as "true" or "false".

Related methods:

  • setAllCaps(boolean)

android:textAppearance

Base text color, typeface, size, and style.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

Related methods:

  • setTextAppearance(int)

android:textColor

Text color.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

Related methods:

  • setTextColor(ColorStateList)

android:textColorHighlight

Color of the text selection highlight.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

Related methods:

  • setHighlightColor(int)

android:textColorHint

Color of the hint text.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

Related methods:

  • setHintTextColor(int)

Text color for links.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

May be a color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

Related methods:

  • setLinkTextColor(int)

android:textCursorDrawable

Reference to a drawable that will be drawn under the insertion cursor.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

Related methods:

  • setTextCursorDrawable(int)

android:textFontWeight

Weight for the font used in the TextView.

May be an integer value, such as "100".

android:textIsSelectable

Indicates that the content of a non-editable text can be selected.

May be a boolean value, such as "true" or "false".

Related methods:

  • isTextSelectable()

android:textScaleX

Sets the horizontal scaling factor for the text.

May be a floating point value, such as "1.2".

Related methods:

  • setTextScaleX(float)

android:textSelectHandle

Reference to a drawable that will be used to display a text selection anchor for positioning the cursor within text.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

Related methods:

  • setTextSelectHandle(Drawable)

android:textSelectHandleLeft

Reference to a drawable that will be used to display a text selection anchor on the left side of a selection region.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

Related methods:

  • setTextSelectHandleLeft(Drawable)

android:textSelectHandleRight

Reference to a drawable that will be used to display a text selection anchor on the right side of a selection region.

May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".

Related methods:

  • setTextSelectHandleRight(int)

android:textSize

Size of the text. Recommended dimension type for text is "sp" for scaled-pixels (example: 15sp).

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

Related methods:

  • setTextSize(float)

android:textStyle

Style (normal, bold, italic, bold|italic) for the text.

Must be one or more (separated by '|') of the following constant values.

ConstantValueDescription
bold 1
italic 2
normal 0

Related methods:

  • setTypeface(Typeface,int)

android:typeface

Typeface (normal, sans, serif, monospace) for the text.

Must be one of the following constant values.

ConstantValueDescription
monospace 3
normal 0
sans 1
serif 2

Related methods:

  • setTypeface(Typeface,int)

android:width

Makes the TextView be exactly this wide. You could get the same effect by specifying this number in the layout parameters.

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

Related methods:

  • setWidth(int)

Constants

AUTO_SIZE_TEXT_TYPE_NONE

Added in API level 26

public static final int AUTO_SIZE_TEXT_TYPE_NONE

The TextView does not auto-size text (default).

Constant Value: 0 (0x00000000)

AUTO_SIZE_TEXT_TYPE_UNIFORM

Added in API level 26

public static final int AUTO_SIZE_TEXT_TYPE_UNIFORM

The TextView scales text size both horizontally and vertically to fit within the container.

Constant Value: 1 (0x00000001)

Public constructors

TextView

Added in API level 1

public TextView (Context context)
Parameters
context Context

TextView

Added in API level 1

public TextView (Context context, 
                AttributeSet attrs)
Parameters
context Context
attrs AttributeSet: This value may be null.

TextView

Added in API level 1

public TextView (Context context, 
                AttributeSet attrs, 
                int defStyleAttr)
Parameters
context Context
attrs AttributeSet: This value may be null.
defStyleAttr int

TextView

Added in API level 21

public TextView (Context context, 
                AttributeSet attrs, 
                int defStyleAttr, 
                int defStyleRes)
Parameters
context Context
attrs AttributeSet: This value may be null.
defStyleAttr int
defStyleRes int

Public methods

addExtraDataToAccessibilityNodeInfo

Added in API level 26

public void addExtraDataToAccessibilityNodeInfo (AccessibilityNodeInfo info, 
                String extraDataKey, 
                Bundle arguments)

Adds extra data to an AccessibilityNodeInfo based on an explicit request for the additional data.

This method only needs overloading if the node is marked as having extra data available.

Parameters
info AccessibilityNodeInfo: The info to which to add the extra data. Never null.
extraDataKey String: A key specifying the type of extra data to add to the info. The extra data should be added to the Bundle returned by the info's AccessibilityNodeInfo#getExtras method. Never null.
arguments Bundle: A Bundle holding any arguments relevant for this request. May be null if the service provided no arguments.

addTextChangedListener

Added in API level 1

public void addTextChangedListener (TextWatcher watcher)

Adds a TextWatcher to the list of those whose methods are called whenever this TextView's text changes.

In 1.0, the TextWatcher#afterTextChanged method was erroneously not called after setText(char[], int, int) calls. Now, doing setText(char[], int, int) if there are any text changed listeners forces the buffer type to Editable if it would not otherwise be and does call this method.

Parameters
watcher TextWatcher

append

Added in API level 1

public final void append (CharSequence text)

Convenience method to append the specified text to the TextView's display buffer, upgrading it to TextView.BufferType.EDITABLE if it was not already editable.

Parameters
text CharSequence: text to be appended to the already displayed text

append

Added in API level 1

public void append (CharSequence text, 
                int start, 
                int end)

Convenience method to append the specified text slice to the TextView's display buffer, upgrading it to TextView.BufferType.EDITABLE if it was not already editable.

Parameters
text CharSequence: text to be appended to the already displayed text
start int: the index of the first character in the text
end int: the index of the character following the last character in the text

See also:

  • Appendable.append(CharSequence, int, int)

autofill

Added in API level 26

public void autofill (AutofillValue value)

Automatically fills the content of this view with the value.

Views support the Autofill Framework mainly by:

  • Providing the metadata defining what the view means and how it can be autofilled.
  • Implementing the methods that autofill the view.

onProvideAutofillStructure(android.view.ViewStructure, int) is responsible for the former, this method is responsible for latter.

This method does nothing by default, but when overridden it typically:

  1. Checks if the provided value matches the expected type (which is defined by getAutofillType()).
  2. Checks if the view is editable - if it isn't, it should return right away.
  3. Call the proper getter method on AutofillValue to fetch the actual value.
  4. Pass the actual value to the equivalent setter in the view.

For example, a text-field view could implement the method this way:

 @Override
 public void autofill(AutofillValue value) {
   if (!value.isText() || !this.isEditable()) {
      return;
   }
   CharSequence text = value.getTextValue();
   if (text != null) {
     this.setText(text);
   }
 }
 

If the value is updated asynchronously, the next call to AutofillManager#notifyValueChanged(View) must happen after the value was changed to the autofilled value. If not, the view will not be considered autofilled.

Note: After this method is called, the value returned by getAutofillValue() must be equal to the value passed to it, otherwise the view will not be highlighted as autofilled.

Parameters
value AutofillValue: value to be autofilled.

beginBatchEdit

Added in API level 3

public void beginBatchEdit ()

bringPointIntoView

Added in API level 3

public boolean bringPointIntoView (int offset)

Move the point, specified by the offset, into the view if it is needed. This has to be called after layout. Returns true if anything changed.

Parameters
offset int
Returns
boolean

cancelLongPress

Added in API level 1

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.

clearComposingText

Added in API level 3

public void clearComposingText ()

Use BaseInputConnection.removeComposingSpans() to remove any IME composing state from this text view.

computeScroll

Added in API level 1

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 object.

debug

Added in API level 1

public void debug (int depth)
Parameters
depth int

didTouchFocusSelect

Added in API level 3

public boolean didTouchFocusSelect ()

Returns true, only while processing a touch gesture, if the initial touch down event caused focus to move to the text view and as a result its selection changed. Only valid while processing the touch gesture of interest, in an editable text view.

Returns
boolean

drawableHotspotChanged

Added in API level 21

public void drawableHotspotChanged (float x, 
                float y)

This function is called whenever the view hotspot changes and needs to be propagated to drawables or child views managed by the view.

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

Be sure to call through to the superclass when overriding this function.
If you override this method you must call through to the superclass implementation.

Parameters
x float: hotspot x coordinate
y float: hotspot y coordinate

endBatchEdit

Added in API level 3

public void endBatchEdit ()

extractText

Added in API level 3

public boolean extractText (ExtractedTextRequest request, 
                ExtractedText outText)

If this TextView contains editable content, extract a portion of it based on the information in request in to outText.

Parameters
request ExtractedTextRequest
outText ExtractedText
Returns
boolean Returns true if the text was successfully extracted, else false.

findViewsWithText

Added in API level 14

public void findViewsWithText (ArrayList<View> outViews, 
                CharSequence searched, 
                int flags)

Finds the Views that contain given text. The containment is case insensitive. The search is performed by either the text that the View renders or the content description that describes the view for accessibility purposes and the view does not render or both. Clients can specify how the search is to be performed via passing the FIND_VIEWS_WITH_TEXT and FIND_VIEWS_WITH_CONTENT_DESCRIPTION flags.

Parameters
outViews ArrayList: The output list of matching Views.
searched CharSequence: The text to match against.
flags int: Value is either 0 or a combination of View.FIND_VIEWS_WITH_TEXT, and View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION

getAccessibilityClassName

Added in API level 23

public CharSequence getAccessibilityClassName ()

Return the class name of this object to be used for accessibility purposes. Subclasses should only override this if they are implementing something that should be seen as a completely new class of view when used by accessibility, unrelated to the class it is deriving from. This is used to fill in AccessibilityNodeInfo.setClassName.

Returns
CharSequence

getAutoLinkMask

Added in API level 1

public final int getAutoLinkMask ()

Gets the autolink mask of the text. See Linkify#ALL and peers for possible values.

Related XML Attributes:

  • android:autoLink
Returns
int

getAutoSizeMaxTextSize

Added in API level 26

public int getAutoSizeMaxTextSize ()

Related XML Attributes:

  • android:autoSizeMaxTextSize
Returns
int the current auto-size maximum text size in pixels (the default is 112sp). Note that if auto-size has not been configured this function returns -1.

See also:

  • setAutoSizeTextTypeUniformWithConfiguration(int, int, int, int)
  • setAutoSizeTextTypeUniformWithPresetSizes(int[], int)

getAutoSizeMinTextSize

Added in API level 26

public int getAutoSizeMinTextSize ()

Related XML Attributes:

  • android:autoSizeMinTextSize
Returns
int the current auto-size minimum text size in pixels (the default is 12sp). Note that if auto-size has not been configured this function returns -1.

See also:

  • setAutoSizeTextTypeUniformWithConfiguration(int, int, int, int)
  • setAutoSizeTextTypeUniformWithPresetSizes(int[], int)

getAutoSizeStepGranularity

Added in API level 26

public int getAutoSizeStepGranularity ()

Related XML Attributes:

  • android:autoSizeStepGranularity
Returns
int the current auto-size step granularity in pixels.

See also:

  • setAutoSizeTextTypeUniformWithConfiguration(int, int, int, int)

getAutoSizeTextAvailableSizes

Added in API level 26

public int[] getAutoSizeTextAvailableSizes ()
Returns
int[] the current auto-size int sizes array (in pixels).

See also:

  • setAutoSizeTextTypeUniformWithConfiguration(int, int, int, int)
  • setAutoSizeTextTypeUniformWithPresetSizes(int[], int)

getAutoSizeTextType

Added in API level 26

public int getAutoSizeTextType ()

Returns the type of auto-size set for this widget.

Related XML Attributes:

  • android:autoSizeTextType
Returns
int an int corresponding to one of the auto-size types: TextView#AUTO_SIZE_TEXT_TYPE_NONE or TextView#AUTO_SIZE_TEXT_TYPE_UNIFORM Value is AUTO_SIZE_TEXT_TYPE_NONE, or AUTO_SIZE_TEXT_TYPE_UNIFORM

See also:

  • setAutoSizeTextTypeWithDefaults(int)
  • setAutoSizeTextTypeUniformWithConfiguration(int, int, int, int)
  • setAutoSizeTextTypeUniformWithPresetSizes(int[], int)

getAutofillHints

Added in API level 26

public String[] getAutofillHints ()

Gets the hints that help an AutofillService determine how to autofill the view with the user's data.

See setAutofillHints(java.lang.String) for more info about these hints.

Returns
String[] The hints set via the attribute or setAutofillHints(java.lang.String), or null if no hints were set.

getAutofillType

Added in API level 26

public int getAutofillType ()

Describes the autofill type of this view, so an AutofillService can create the proper AutofillValue when autofilling the view.

By default returns AUTOFILL_TYPE_NONE, but views should override it to properly support the Autofill Framework.

Returns
int Value is View.AUTOFILL_TYPE_NONE, View.AUTOFILL_TYPE_TEXT, View.AUTOFILL_TYPE_TOGGLE, View.AUTOFILL_TYPE_LIST, or View.AUTOFILL_TYPE_DATE

getAutofillValue

Added in API level 26

public AutofillValue getAutofillValue ()

Gets the TextView's current text for AutoFill. The value is trimmed to 100K chars if longer.

Returns
AutofillValue current text, null if the text is not editable

See also:

  • View.getAutofillValue()

getBaseline

Added in API level 1

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
int the offset of the baseline within the widget's bounds or -1 if baseline alignment is not supported

getBreakStrategy

Added in API level 23

public int getBreakStrategy ()

Gets the current strategy for breaking paragraphs into lines.

Related XML Attributes:

  • android:breakStrategy
Returns
int the current strategy for breaking paragraphs into lines. Value is LineBreaker.BREAK_STRATEGY_SIMPLE, LineBreaker.BREAK_STRATEGY_HIGH_QUALITY, or LineBreaker.BREAK_STRATEGY_BALANCED

See also:

  • setBreakStrategy(int)

getCompoundDrawablePadding

Added in API level 1

public int getCompoundDrawablePadding ()

Returns the padding between the compound drawables and the text.

Related XML Attributes:

  • android:drawablePadding
Returns
int

getCompoundDrawableTintBlendMode

Added in API level 29

public BlendMode getCompoundDrawableTintBlendMode ()

Returns the blending mode used to apply the tint to the compound drawables, if specified.

Related XML Attributes:

  • android:drawableTintMode
Returns
BlendMode the blending mode used to apply the tint to the compound drawables This value may be null.

See also:

  • setCompoundDrawableTintBlendMode(BlendMode)

getCompoundDrawableTintList

Added in API level 23

public ColorStateList getCompoundDrawableTintList ()

Related XML Attributes:

  • android:drawableTint
Returns
ColorStateList the tint applied to the compound drawables

See also:

  • setCompoundDrawableTintList(ColorStateList)

getCompoundDrawableTintMode

Added in API level 23

public PorterDuff.Mode getCompoundDrawableTintMode ()

Returns the blending mode used to apply the tint to the compound drawables, if specified.

Related XML Attributes:

  • android:drawableTintMode
Returns
PorterDuff.Mode the blending mode used to apply the tint to the compound drawables

See also:

  • setCompoundDrawableTintMode(PorterDuff.Mode)

getCompoundDrawables

Added in API level 1

public Drawable[] getCompoundDrawables ()

Returns drawables for the left, top, right, and bottom borders.

Related XML Attributes:

  • android:drawableLeft
  • android:drawableTop
  • android:drawableRight
  • android:drawableBottom
Returns
Drawable[] This value cannot be null.

getCompoundDrawablesRelative

Added in API level 17

public Drawable[] getCompoundDrawablesRelative ()

Returns drawables for the start, top, end, and bottom borders.

Related XML Attributes:

  • android:drawableStart
  • android:drawableTop
  • android:drawableEnd
  • android:drawableBottom
Returns
Drawable[] This value cannot be null.

getCompoundPaddingBottom

Added in API level 1

public int getCompoundPaddingBottom ()

Returns the bottom padding of the view, plus space for the bottom Drawable if any.

Returns
int

getCompoundPaddingEnd

Added in API level 17

public int getCompoundPaddingEnd ()

Returns the end padding of the view, plus space for the end Drawable if any.

Returns
int

getCompoundPaddingLeft

Added in API level 1

public int getCompoundPaddingLeft ()

Returns the left padding of the view, plus space for the left Drawable if any.

Returns
int

getCompoundPaddingRight

Added in API level 1

public int getCompoundPaddingRight ()

Returns the right padding of the view, plus space for the right Drawable if any.

Returns
int

getCompoundPaddingStart

Added in API level 17

public int getCompoundPaddingStart ()

Returns the start padding of the view, plus space for the start Drawable if any.

Returns
int

getCompoundPaddingTop

Added in API level 1

public int getCompoundPaddingTop ()

Returns the top padding of the view, plus space for the top Drawable if any.

Returns
int

getCurrentHintTextColor

Added in API level 1

public final int getCurrentHintTextColor ()

Return the current color selected to paint the hint text.

Returns
int Returns the current hint text color.

getCurrentTextColor

Added in API level 1

public final int getCurrentTextColor ()

Return the current color selected for normal text.

Returns
int Returns the current text color.

getCustomInsertionActionModeCallback

Added in API level 23

public ActionMode.Callback getCustomInsertionActionModeCallback ()

Retrieves the value set in setCustomInsertionActionModeCallback(ActionMode.Callback). Default is null.

Returns
ActionMode.Callback The current custom insertion callback.

getCustomSelectionActionModeCallback

Added in API level 11

public ActionMode.Callback getCustomSelectionActionModeCallback ()

Retrieves the value set in setCustomSelectionActionModeCallback(ActionMode.Callback). Default is null.

Returns
ActionMode.Callback The current custom selection callback.

getEditableText

Added in API level 3

public Editable getEditableText ()

Return the text that TextView is displaying as an Editable object. If the text is not editable, null is returned.

Returns
Editable

See also:

  • getText()

getEllipsize

Added in API level 1

public TextUtils.TruncateAt getEllipsize ()

Returns where, if anywhere, words that are longer than the view is wide should be ellipsized.

Returns
TextUtils.TruncateAt

getError

Added in API level 1

public CharSequence getError ()

Returns the error message that was set to be displayed with setError(CharSequence), or null if no error was set or if it the error was cleared by the widget after user input.

Returns
CharSequence

getExtendedPaddingBottom

Added in API level 1

public int getExtendedPaddingBottom ()

Returns the extended bottom padding of the view, including both the bottom Drawable if any and any extra space to keep more than maxLines of text from showing. It is only valid to call this after measuring.

Returns
int

getExtendedPaddingTop

Added in API level 1

public int getExtendedPaddingTop ()

Returns the extended top padding of the view, including both the top Drawable if any and any extra space to keep more than maxLines of text from showing. It is only valid to call this after measuring.

Returns
int

getFilters

Added in API level 1

public InputFilter[] getFilters ()

Returns the current list of input filters.

Related XML Attributes:

  • android:maxLength
Returns
InputFilter[]

getFirstBaselineToTopHeight

Added in API level 28

public int getFirstBaselineToTopHeight ()

Returns the distance between the first text baseline and the top of this TextView.

Related XML Attributes:

  • android:firstBaselineToTopHeight
Returns
int

See also:

  • setFirstBaselineToTopHeight(int)

getFocusedRect

Added in API level 1

public void getFocusedRect (Rect r)

When a view has focus and the user navigates away from it, the next view is searched for starting from the rectangle filled in by this method. By default, the rectangle is the getDrawingRect(android.graphics.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 Rect: The rectangle to fill in, in this view's coordinates.

getFontFeatureSettings

Added in API level 21

public String getFontFeatureSettings ()

Returns the font feature settings. The format is the same as the CSS font-feature-settings attribute: https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop

Returns
String the currently set font feature settings. Default is null.

See also:

  • setFontFeatureSettings(String)
  • Paint.setFontFeatureSettings(String)

getFontVariationSettings

Added in API level 26

public String getFontVariationSettings ()

Returns the font variation settings.

Returns
String the currently set font variation settings. Returns null if no variation is specified.

See also:

  • setFontVariationSettings(String)
  • Paint.setFontVariationSettings(String)

getFreezesText

Added in API level 1

public boolean getFreezesText ()

Return whether this text view is including its entire text contents in frozen icicles. For EditText it always returns true.

Returns
boolean Returns true if text is included, false if it isn't.

See also:

  • setFreezesText(boolean)

getGravity

Added in API level 1

public int getGravity ()

Returns the horizontal and vertical alignment of this TextView.

Related XML Attributes:

  • android:gravity
Returns
int

See also:

  • Gravity

getHighlightColor

Added in API level 16

public int getHighlightColor ()

Related XML Attributes:

  • android:textColorHighlight
Returns
int the color used to display the selection highlight

See also:

  • setHighlightColor(int)

getHint

Added in API level 1

public CharSequence getHint ()

Returns the hint that is displayed when the text of the TextView is empty.

Related XML Attributes:

  • android:hint
Returns
CharSequence

getHintTextColors

Added in API level 1

public final ColorStateList getHintTextColors ()

Related XML Attributes:

  • android:textColorHint
Returns
ColorStateList the color of the hint text, for the different states of this TextView.

See also:

  • setHintTextColor(ColorStateList)
  • setHintTextColor(int)
  • setTextColor(ColorStateList)
  • setLinkTextColor(ColorStateList)

getHyphenationFrequency

Added in API level 23

public int getHyphenationFrequency ()

Gets the current frequency of automatic hyphenation to be used when determining word breaks.

Related XML Attributes:

  • android:hyphenationFrequency
Returns
int the current frequency of automatic hyphenation to be used when determining word breaks. Value is Layout.HYPHENATION_FREQUENCY_NORMAL, Layout.HYPHENATION_FREQUENCY_NORMAL_FAST, Layout.HYPHENATION_FREQUENCY_FULL, Layout.HYPHENATION_FREQUENCY_FULL_FAST, or Layout.HYPHENATION_FREQUENCY_NONE

See also:

  • setHyphenationFrequency(int)

getImeActionId

Added in API level 3

public int getImeActionId ()

Get the IME action ID previous set with setImeActionLabel(CharSequence, int).

Returns
int

See also:

  • setImeActionLabel(CharSequence, int)
  • EditorInfo

getImeActionLabel

Added in API level 3

public CharSequence getImeActionLabel ()

Get the IME action label previous set with setImeActionLabel(CharSequence, int).

Returns
CharSequence

See also:

  • setImeActionLabel(CharSequence, int)
  • EditorInfo

getImeHintLocales

Added in API level 24

public LocaleList getImeHintLocales ()
Returns
LocaleList The current languages list "hint". null when no "hint" is available.

See also:

  • setImeHintLocales(LocaleList)
  • EditorInfo.hintLocales

getImeOptions

Added in API level 3

public int getImeOptions ()

Get the type of the Input Method Editor (IME).

Returns
int the type of the IME

See also:

  • setImeOptions(int)
  • EditorInfo

getIncludeFontPadding

Added in API level 16

public boolean getIncludeFontPadding ()

Gets whether the TextView includes extra top and bottom padding to make room for accents that go above the normal ascent and descent.

Related XML Attributes:

  • android:includeFontPadding
Returns
boolean

See also:

  • setIncludeFontPadding(boolean)

getInputExtras

Added in API level 3

public Bundle getInputExtras (boolean create)

Retrieve the input extras currently associated with the text view, which can be viewed as well as modified.

Related XML Attributes:

  • android:editorExtras
Parameters
create boolean: If true, the extras will be created if they don't already exist. Otherwise, null will be returned if none have been created.
Returns
Bundle

See also:

  • setInputExtras(int)
  • EditorInfo.extras

getInputType

Added in API level 3

public int getInputType ()

Get the type of the editable content.

Returns
int

See also:

  • setInputType(int)
  • InputType

getJustificationMode

Added in API level 26

public int getJustificationMode ()
Returns
int true if currently paragraph justification mode. Value is LineBreaker.JUSTIFICATION_MODE_NONE, or LineBreaker.JUSTIFICATION_MODE_INTER_WORD

See also:

  • setJustificationMode(int)

getKeyListener

Added in API level 1

public final KeyListener getKeyListener ()

Gets the current KeyListener for the TextView. This will frequently be null for non-EditText TextViews.

Related XML Attributes:

  • android:numeric
  • android:digits
  • android:phoneNumber
  • android:inputMethod
  • android:capitalize
  • android:autoText
Returns
KeyListener the current key listener for this TextView.

getLastBaselineToBottomHeight

Added in API level 28

public int getLastBaselineToBottomHeight ()

Returns the distance between the last text baseline and the bottom of this TextView.

Related XML Attributes:

  • android:lastBaselineToBottomHeight
Returns
int

See also:

  • setLastBaselineToBottomHeight(int)

getLayout

Added in API level 1

public final Layout getLayout ()

Gets the Layout that is currently being used to display the text. This value can be null if the text or width has recently changed.

Returns
Layout The Layout that is currently being used to display the text.

getLetterSpacing

Added in API level 21

public float getLetterSpacing ()

Gets the text letter-space value, which determines the spacing between characters. The value returned is in ems. Normally, this value is 0.0.

Returns
float The text letter-space value in ems.

See also:

  • setLetterSpacing(float)
  • Paint.setLetterSpacing(float)

getLineBounds

Added in API level 1

public int getLineBounds (int line, 
                Rect bounds)

Return the baseline for the specified line (0...getLineCount() - 1) If bounds is not null, return the top, left, right, bottom extents of the specified line in it. If the internal Layout has not been built, return 0 and set bounds to (0, 0, 0, 0)

Parameters
line int: which line to examine (0..getLineCount() - 1)
bounds Rect: Optional. If not null, it returns the extent of the line
Returns
int the Y-coordinate of the baseline

getLineBreakStyle

Added in API level 33

public int getLineBreakStyle ()

Gets the current line-break style for text wrapping.

Returns
int The line-break style to be used for text wrapping. Value is LineBreakConfig.LINE_BREAK_STYLE_NONE, LineBreakConfig.LINE_BREAK_STYLE_LOOSE, LineBreakConfig.LINE_BREAK_STYLE_NORMAL, or LineBreakConfig.LINE_BREAK_STYLE_STRICT

getLineBreakWordStyle

Added in API level 33

public int getLineBreakWordStyle ()

Gets the current line-break word style for text wrapping.

Returns
int The line-break word style to be used for text wrapping. Value is LineBreakConfig.LINE_BREAK_WORD_STYLE_NONE, or LineBreakConfig.LINE_BREAK_WORD_STYLE_PHRASE

getLineCount

Added in API level 1

public int getLineCount ()

Return the number of lines of text, or 0 if the internal Layout has not been built.

Returns
int

getLineHeight

Added in API level 1

public int getLineHeight ()

Gets the vertical distance between lines of text, in pixels. Note that markup within the text can cause individual lines to be taller or shorter than this height, and the layout may contain additional first-or last-line padding.

Returns
int The height of one standard line in pixels.

getLineSpacingExtra

Added in API level 16

public float getLineSpacingExtra ()

Gets the line spacing extra space

Related XML Attributes:

  • android:lineSpacingExtra
Returns
float the extra space that is added to the height of each lines of this TextView.

See also:

  • setLineSpacing(float, float)
  • getLineSpacingMultiplier()

getLineSpacingMultiplier

Added in API level 16

public float getLineSpacingMultiplier ()

Gets the line spacing multiplier

Related XML Attributes:

  • android:lineSpacingMultiplier
Returns
float the value by which each line's height is multiplied to get its actual height.

See also:

  • setLineSpacing(float, float)
  • getLineSpacingExtra()

getLinkTextColors

Added in API level 1

public final ColorStateList getLinkTextColors ()

Related XML Attributes:

  • android:textColorLink
Returns
ColorStateList the list of colors used to paint the links in the text, for the different states of this TextView

See also:

  • setLinkTextColor(ColorStateList)
  • setLinkTextColor(int)

getLinksClickable

Added in API level 1

public final boolean getLinksClickable ()

Returns whether the movement method will automatically be set to LinkMovementMethod if setAutoLinkMask(int) has been set to nonzero and links are detected in setText(char[], int, int). The default is true.

Related XML Attributes:

  • android:linksClickable
Returns
boolean

getMarqueeRepeatLimit

Added in API level 16

public int getMarqueeRepeatLimit ()

Gets the number of times the marquee animation is repeated. Only meaningful if the TextView has marquee enabled.

Related XML Attributes:

  • android:marqueeRepeatLimit
Returns
int the number of times the marquee animation is repeated. -1 if the animation repeats indefinitely

See also:

  • setMarqueeRepeatLimit(int)

getMaxEms

Added in API level 16

public int getMaxEms ()

Returns the maximum width of TextView in terms of ems or -1 if the maximum width was set using setMaxWidth(int) or setWidth(int).

Related XML Attributes:

  • android:maxEms
Returns
int the maximum width of TextView in terms of ems or -1 if the maximum width is not defined in ems

See also:

  • setMaxEms(int)
  • setEms(int)

getMaxHeight

Added in API level 16

public int getMaxHeight ()

Returns the maximum height of TextView in terms of pixels or -1 if the maximum height was set using setMaxLines(int) or setLines(int).

Related XML Attributes:

  • android:maxHeight
Returns
int the maximum height of TextView in terms of pixels or -1 if the maximum height is not defined in pixels

See also:

  • setMaxHeight(int)
  • setHeight(int)

getMaxLines

Added in API level 16

public int getMaxLines ()

Returns the maximum height of TextView in terms of number of lines or -1 if the maximum height was set using setMaxHeight(int) or setHeight(int).

Related XML Attributes:

  • android:maxLines
Returns
int the maximum height of TextView in terms of number of lines. -1 if the maximum height is not defined in lines.

See also:

  • setMaxLines(int)
  • setLines(int)

getMaxWidth

Added in API level 16

public int getMaxWidth ()

Returns the maximum width of TextView in terms of pixels or -1 if the maximum width was set using setMaxEms(int) or setEms(int).

Related XML Attributes:

  • android:maxWidth
Returns
int the maximum width of TextView in terms of pixels. -1 if the maximum width is not defined in pixels

See also:

  • setMaxWidth(int)
  • setWidth(int)

getMinEms

Added in API level 16

public int getMinEms ()

Returns the minimum width of TextView in terms of ems or -1 if the minimum width was set using setMinWidth(int) or setWidth(int).

Related XML Attributes:

  • android:minEms
Returns
int the minimum width of TextView in terms of ems. -1 if the minimum width is not defined in ems

See also:

  • setMinEms(int)
  • setEms(int)

getMinHeight

Added in API level 16

public int getMinHeight ()

Returns the minimum height of TextView in terms of pixels or -1 if the minimum height was set using setMinLines(int) or setLines(int).

Related XML Attributes:

  • android:minHeight
Returns
int the minimum height of TextView in terms of pixels or -1 if the minimum height is not defined in pixels

See also:

  • setMinHeight(int)
  • setHeight(int)

getMinLines

Added in API level 16

public int getMinLines ()

Returns the minimum height of TextView in terms of number of lines or -1 if the minimum height was set using setMinHeight(int) or setHeight(int).

Related XML Attributes:

  • android:minLines
Returns
int the minimum height of TextView in terms of number of lines or -1 if the minimum height is not defined in lines

See also:

  • setMinLines(int)
  • setLines(int)

getMinWidth

Added in API level 16

public int getMinWidth ()

Returns the minimum width of TextView in terms of pixels or -1 if the minimum width was set using setMinEms(int) or setEms(int).

Related XML Attributes:

  • android:minWidth
Returns
int the minimum width of TextView in terms of pixels or -1 if the minimum width is not defined in pixels

See also:

  • setMinWidth(int)
  • setWidth(int)

getMovementMethod

Added in API level 1

public final MovementMethod getMovementMethod ()

Gets the MovementMethod being used for this TextView, which provides positioning, scrolling, and text selection functionality. This will frequently be null for non-EditText TextViews.

Returns
MovementMethod the movement method being used for this TextView.

See also:

  • MovementMethod

getOffsetForPosition

Added in API level 14

public int getOffsetForPosition (float x, 
                float y)

Get the character offset closest to the specified absolute position. A typical use case is to pass the result of MotionEvent#getX() and MotionEvent#getY() to this method.

Parameters
x float: The horizontal absolute position of a point on screen
y float: The vertical absolute position of a point on screen
Returns
int the character offset for the character whose position is closest to the specified position. Returns -1 if there is no layout.

getPaint

Added in API level 1

public TextPaint getPaint ()

Gets the TextPaint used for the text. Use this only to consult the Paint's properties and not to change them.

Returns
TextPaint The base paint used for the text.

getPaintFlags

Added in API level 1

public int getPaintFlags ()

Gets the flags on the Paint being used to display the text.

Returns
int The flags on the Paint being used to display the text.

See also:

  • Paint.getFlags()

getPrivateImeOptions

Added in API level 3

public String getPrivateImeOptions ()

Get the private type of the content.

Returns
String

See also:

  • setPrivateImeOptions(String)
  • EditorInfo.privateImeOptions

getSelectionEnd

Added in API level 1

public int getSelectionEnd ()

Convenience for Selection#getSelectionEnd.

Returns
int

getSelectionStart

Added in API level 1

public int getSelectionStart ()

Convenience for Selection#getSelectionStart.

Returns
int

getShadowColor

Added in API level 16

public int getShadowColor ()

Gets the color of the shadow layer.

Related XML Attributes:

  • android:shadowColor
Returns
int the color of the shadow layer

See also:

  • setShadowLayer(float, float, float, int)

getShadowDx

Added in API level 16

public float getShadowDx ()

Related XML Attributes:

  • android:shadowDx
Returns
float the horizontal offset of the shadow layer

See also:

  • setShadowLayer(float, float, float, int)

getShadowDy

Added in API level 16

public float getShadowDy ()

Gets the vertical offset of the shadow layer.

Related XML Attributes:

  • android:shadowDy
Returns
float The vertical offset of the shadow layer.

See also:

  • setShadowLayer(float, float, float, int)

getShadowRadius

Added in API level 16

public float getShadowRadius ()

Gets the radius of the shadow layer.

Related XML Attributes:

  • android:shadowRadius
Returns
float the radius of the shadow layer. If 0, the shadow layer is not visible

See also:

  • setShadowLayer(float, float, float, int)

getShowSoftInputOnFocus

Added in API level 21

public final boolean getShowSoftInputOnFocus ()

Returns whether the soft input method will be made visible when this TextView gets focused. The default is true.

Returns
boolean

getText

Added in API level 1

public CharSequence getText ()

Return the text that TextView is displaying. If setText(java.lang.CharSequence) was called with an argument of BufferType.SPANNABLE or BufferType.EDITABLE, you can cast the return value from this method to Spannable or Editable, respectively.

The content of the return value should not be modified. If you want a modifiable one, you should make your own copy first.

Related XML Attributes:

  • android:text
Returns
CharSequence The text displayed by the text view.

getTextClassifier

Added in API level 26

public TextClassifier getTextClassifier ()

Returns the TextClassifier used by this TextView. If no TextClassifier has been set, this TextView uses the default set by the TextClassificationManager.

Returns
TextClassifier This value cannot be null.

getTextColors

Added in API level 1

public final ColorStateList getTextColors ()

Gets the text colors for the different states (normal, selected, focused) of the TextView.

Related XML Attributes:

  • android:textColor
Returns
ColorStateList

See also:

  • setTextColor(ColorStateList)
  • setTextColor(int)

getTextCursorDrawable

Added in API level 29

public Drawable getTextCursorDrawable ()

Returns the Drawable corresponding to the text cursor. Note that any change applied to the cursor Drawable will not be visible until the cursor is hidden and then drawn again.

Related XML Attributes:

  • android:textCursorDrawable
Returns
Drawable the text cursor drawable This value may be null.

See also:

  • setTextCursorDrawable(Drawable)
  • setTextCursorDrawable(int)

getTextDirectionHeuristic

Added in API level 29

public TextDirectionHeuristic getTextDirectionHeuristic ()

Returns resolved TextDirectionHeuristic that will be used for text layout. The TextDirectionHeuristic that is used by TextView is only available after View.getTextDirection() and View.getLayoutDirection() is resolved. Therefore the return value may not be the same as the one TextView uses if the View's layout direction is not resolved or detached from parent root view.

Returns
TextDirectionHeuristic This value cannot be null.

getTextLocale

Added in API level 17

public Locale getTextLocale ()

Get the default primary Locale of the text in this TextView. This will always be the first member of getTextLocales().

Returns
Locale the default primary Locale of the text in this TextView. This value cannot be null.

getTextLocales

Added in API level 24

public LocaleList getTextLocales ()

Get the default LocaleList of the text in this TextView.

Returns
LocaleList the default LocaleList of the text in this TextView. This value cannot be null.

getTextMetricsParams

Added in API level 28

public PrecomputedText.Params getTextMetricsParams ()

Gets the parameters for text layout precomputation, for use with PrecomputedText.

Returns
PrecomputedText.Params a current PrecomputedText.Params This value cannot be null.

See also:

  • PrecomputedText

getTextScaleX

Added in API level 1

public float getTextScaleX ()

Gets the extent by which text should be stretched horizontally. This will usually be 1.0.

Returns
float The horizontal scale factor.

getTextSelectHandle

Added in API level 29

public Drawable getTextSelectHandle ()

Returns the Drawable corresponding to the selection handle used for positioning the cursor within text. Note that any change applied to the handle Drawable will not be visible until the handle is hidden and then drawn again.

Related XML Attributes:

  • android:textSelectHandle
Returns
Drawable the text select handle drawable This value may be null.

See also:

  • setTextSelectHandle(Drawable)
  • setTextSelectHandle(int)

getTextSelectHandleLeft

Added in API level 29

public Drawable getTextSelectHandleLeft ()

Returns the Drawable corresponding to the left handle used for selecting text. Note that any change applied to the handle Drawable will not be visible until the handle is hidden and then drawn again.

Related XML Attributes:

  • android:textSelectHandleLeft
Returns
Drawable the left text selection handle drawable This value may be null.

See also:

  • setTextSelectHandleLeft(Drawable)
  • setTextSelectHandleLeft(int)

getTextSelectHandleRight

Added in API level 29

public Drawable getTextSelectHandleRight ()

Returns the Drawable corresponding to the right handle used for selecting text. Note that any change applied to the handle Drawable will not be visible until the handle is hidden and then drawn again.

Related XML Attributes:

  • android:textSelectHandleRight
Returns
Drawable the right text selection handle drawable This value may be null.

See also:

  • setTextSelectHandleRight(Drawable)
  • setTextSelectHandleRight(int)

getTextSize

Added in API level 1

public float getTextSize ()
Returns
float the size (in pixels) of the default text size in this TextView.

getTextSizeUnit

Added in API level 30

public int getTextSizeUnit ()

Gets the text size unit defined by the developer. It may be specified in resources or be passed as the unit argument of setTextSize(int, float) at runtime.

Returns
int the dimension type of the text size unit originally defined.

See also:

  • TypedValue.TYPE_DIMENSION

getTotalPaddingBottom

Added in API level 1

public int getTotalPaddingBottom ()

Returns the total bottom padding of the view, including the bottom Drawable if any, the extra space to keep more than maxLines from showing, and the vertical offset for gravity, if any.

Returns
int

getTotalPaddingEnd

Added in API level 17

public int getTotalPaddingEnd ()

Returns the total end padding of the view, including the end Drawable if any.

Returns
int

getTotalPaddingLeft

Added in API level 1

public int getTotalPaddingLeft ()

Returns the total left padding of the view, including the left Drawable if any.

Returns
int

getTotalPaddingRight

Added in API level 1

public int getTotalPaddingRight ()

Returns the total right padding of the view, including the right Drawable if any.

Returns
int

getTotalPaddingStart

Added in API level 17

public int getTotalPaddingStart ()

Returns the total start padding of the view, including the start Drawable if any.

Returns
int

getTotalPaddingTop

Added in API level 1

public int getTotalPaddingTop ()

Returns the total top padding of the view, including the top Drawable if any, the extra space to keep more than maxLines from showing, and the vertical offset for gravity, if any.

Returns
int

getTransformationMethod

Added in API level 1

public final TransformationMethod getTransformationMethod ()

Gets the current TransformationMethod for the TextView. This is frequently null, except for single-line and password fields.

Related XML Attributes:

  • android:password
  • android:singleLine
Returns
TransformationMethod the current transformation method for this TextView.

getTypeface

Added in API level 1

public Typeface getTypeface ()

Gets the current Typeface that is used to style the text.

Related XML Attributes:

  • android:fontFamily
  • android:typeface
  • android:textStyle
Returns
Typeface The current Typeface.

See also:

  • setTypeface(Typeface)

getUrls

Added in API level 1

public URLSpan[] getUrls ()

Returns the list of URLSpans attached to the text (by Linkify or otherwise) if any. You can call URLSpan#getURL on them to find where they link to or use Spanned#getSpanStart and Spanned#getSpanEnd to find the region of the text they are attached to.

Returns
URLSpan[]

hasOverlappingRendering

Added in API level 16

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
boolean true if the content in this view might overlap, false otherwise.

hasSelection

Added in API level 1

public boolean hasSelection ()

Return true iff there is a selection of nonzero length inside this text view.

Returns
boolean

invalidateDrawable

Added in API level 1

public void invalidateDrawable (Drawable drawable)

Invalidates the specified Drawable.

Parameters
drawable Drawable: This value cannot be null.

isAllCaps

Added in API level 28

public boolean isAllCaps ()

Checks whether the transformation method applied to this TextView is set to ALL CAPS.

Returns
boolean Whether the current transformation method is for ALL CAPS.

See also:

  • setAllCaps(boolean)
  • setTransformationMethod(TransformationMethod)

isCursorVisible

Added in API level 16

public boolean isCursorVisible ()

Related XML Attributes:

  • android:cursorVisible
Returns
boolean whether or not the cursor is visible (assuming this TextView is editable). This method may return false when the IME is consuming the input even if the mEditor.mCursorVisible attribute is true or #setCursorVisible(true) is called.

See also:

  • setCursorVisible(boolean)

isElegantTextHeight

Added in API level 28

public boolean isElegantTextHeight ()

Get the value of the TextView's elegant height metrics flag. This setting selects font variants that have not been compacted to fit Latin-based vertical metrics, and also increases top and bottom bounds to provide more space.

Returns
boolean true if the elegant height metrics flag is set.

See also:

  • setElegantTextHeight(boolean)
  • Paint.setElegantTextHeight(boolean)

isFallbackLineSpacing

Added in API level 28

public boolean isFallbackLineSpacing ()

Related XML Attributes:

  • android:fallbackLineSpacing
Returns
boolean whether fallback line spacing is enabled, true by default

See also:

  • setFallbackLineSpacing(boolean)

isHorizontallyScrollable

Added in API level 29

public final boolean isHorizontallyScrollable ()

Returns whether the text is allowed to be wider than the View. If false, the text will be wrapped to the width of the View.

Related XML Attributes:

  • android:scrollHorizontally
Returns
boolean

See also:

  • setHorizontallyScrolling(boolean)

isInputMethodTarget

Added in API level 3

public boolean isInputMethodTarget ()

Returns whether this text view is a current input method target. The default implementation just checks with InputMethodManager.

Returns
boolean True if the TextView is a current input method target; false otherwise.

isSingleLine

Added in API level 29

public boolean isSingleLine ()

Returns if the text is constrained to a single horizontally scrolling line ignoring new line characters instead of letting it wrap onto multiple lines.

Related XML Attributes:

  • android:singleLine
Returns
boolean

isSuggestionsEnabled

Added in API level 14

public boolean isSuggestionsEnabled ()

Return whether or not suggestions are enabled on this TextView. The suggestions are generated by the IME or by the spell checker as the user types. This is done by adding SuggestionSpans to the text. When suggestions are enabled (default), this list of suggestions will be displayed when the user asks for them on these parts of the text. This value depends on the inputType of this TextView. The class of the input type must be InputType#TYPE_CLASS_TEXT. In addition, the type variation must be one of InputType#TYPE_TEXT_VARIATION_NORMAL, InputType#TYPE_TEXT_VARIATION_EMAIL_SUBJECT, InputType#TYPE_TEXT_VARIATION_LONG_MESSAGE, InputType#TYPE_TEXT_VARIATION_SHORT_MESSAGE or InputType#TYPE_TEXT_VARIATION_WEB_EDIT_TEXT. And finally, the InputType#TYPE_TEXT_FLAG_NO_SUGGESTIONS flag must not be set.

Returns
boolean true if the suggestions popup window is enabled, based on the inputType.

isTextSelectable

Added in API level 11

public boolean isTextSelectable ()

Returns the state of the textIsSelectable flag (See setTextIsSelectable()). Although you have to set this flag to allow users to select and copy text in a non-editable TextView, the content of an EditText can always be selected, independently of the value of this flag.

Related XML Attributes:

  • android:textIsSelectable
Returns
boolean True if the text displayed in this TextView can be selected by the user.

jumpDrawablesToCurrentState

Added in API level 11

public void jumpDrawablesToCurrentState ()

Call Drawable.jumpToCurrentState() on all Drawable objects associated with this view.

Also calls StateListAnimator#jumpToCurrentState() if there is a StateListAnimator attached to this view.
If you override this method you must call through to the superclass implementation.

length

Added in API level 1

public int length ()

Returns the length, in characters, of the text managed by this TextView

Returns
int The length of the text managed by the TextView in characters.

moveCursorToVisibleOffset

Added in API level 3

public boolean moveCursorToVisibleOffset ()

Move the cursor, if needed, so that it is at an offset that is visible to the user. This will not move the cursor if it represents more than one character (a selection range). This will only work if the TextView contains spannable text; otherwise it will do nothing.

Returns
boolean True if the cursor was actually moved, false otherwise.

onBeginBatchEdit

Added in API level 3

public void onBeginBatchEdit ()

Called by the framework in response to a request to begin a batch of edit operations through a call to link beginBatchEdit().

onCheckIsTextEditor

Added in API level 3

public boolean onCheckIsTextEditor ()

Check whether the called view is a text editor, in which case it would make sense to automatically display a soft input window for it. Subclasses should override this if they implement onCreateInputConnection(android.view.inputmethod.EditorInfo) to return true if a call on that method would return a non-null InputConnection, and they are really a first-class editor that the user would normally start typing on when the go into a window containing your view.

The default implementation always returns false. This does not mean that its onCreateInputConnection(android.view.inputmethod.EditorInfo) will not be called or the user can not otherwise perform edits on your view; it is just a hint to the system that this is not the primary purpose of this view.

Returns
boolean Returns true if this view is a text editor, else false.

onCommitCompletion

Added in API level 3

public void onCommitCompletion (CompletionInfo text)

Called by the framework in response to a text completion from the current input method, provided by it calling InputConnection.commitCompletion(). The default implementation does nothing; text views that are supporting auto-completion should override this to do their desired behavior.

Parameters
text CompletionInfo: The auto complete text the user has selected.

onCommitCorrection

Added in API level 11

public void onCommitCorrection (CorrectionInfo info)

Called by the framework in response to a text auto-correction (such as fixing a typo using a dictionary) from the current input method, provided by it calling InputConnection.commitCorrection(). The default implementation flashes the background of the corrected word to provide feedback to the user.

Parameters
info CorrectionInfo: The auto correct info about the text that was corrected.

onCreateInputConnection

Added in API level 3

public InputConnection onCreateInputConnection (EditorInfo outAttrs)

Create a new InputConnection for an InputMethod to interact with the view. The default implementation returns null, since it doesn't support input methods. You can override this to implement such support. This is only needed for views that take focus and text input.

When implementing this, you probably also want to implement onCheckIsTextEditor() to indicate you will return a non-null InputConnection.

Also, take good care to fill in the EditorInfo object correctly and in its entirety, so that the connected IME can rely on its values. For example, EditorInfo.initialSelStart and EditorInfo.initialSelEnd members must be filled in with the correct cursor position for IMEs to work correctly with your application.

Parameters
outAttrs EditorInfo: Fill in with attribute information about the connection.
Returns
InputConnection

onCreateViewTranslationRequest

Added in API level 31

public void onCreateViewTranslationRequest (int[] supportedFormats, 
                Consumer<ViewTranslationRequest> requestsCollector)

Collects a ViewTranslationRequest which represents the content to be translated in the view.

NOTE: When overriding the method, it should not collect a request to translate this TextView if it is displaying a password.

Parameters
supportedFormats int: the supported translation format. The value could be TranslationSpec.DATA_FORMAT_TEXT. This value cannot be null.
requestsCollector Consumer: Consumer to receiver the ViewTranslationRequest which contains the information to be translated. This value cannot be null.

onDragEvent

Added in API level 11

public boolean onDragEvent (DragEvent event)

Handles drag events sent by the system following a call to startDragAndDrop().

If this text view is not editable, delegates to the default View#onDragEvent implementation.

If this text view is editable, accepts all drag actions (returns true for an ACTION_DRAG_STARTED event and all subsequent drag events). While the drag is in progress, updates the cursor position to follow the touch location. Once a drop event is received, handles content insertion via View.performReceiveContent(ContentInfo).

Parameters
event DragEvent: The DragEvent sent by the system. The DragEvent.getAction() method returns an action type constant defined in DragEvent, indicating the type of drag event represented by this object.
Returns
boolean Returns true if this text view is editable and delegates to super otherwise. See View#onDragEvent.

onEditorAction

Added in API level 3

public void onEditorAction (int actionCode)

Called when an attached input method calls InputConnection.performEditorAction() for this text view. The default implementation will call your action listener supplied to setOnEditorActionListener(TextView.OnEditorActionListener), or perform a standard operation for EditorInfo.IME_ACTION_NEXT, EditorInfo.IME_ACTION_PREVIOUS, or EditorInfo.IME_ACTION_DONE.

For backwards compatibility, if no IME options have been set and the text view would not normally advance focus on enter, then the NEXT and DONE actions received here will be turned into an enter key down/up pair to go through the normal key handling.

Parameters
actionCode int: The code of the action being performed.

See also:

  • setOnEditorActionListener(TextView.OnEditorActionListener)

onEndBatchEdit

Added in API level 3

public void onEndBatchEdit ()

Called by the framework in response to a request to end a batch of edit operations through a call to link endBatchEdit().

onGenericMotionEvent

Added in API level 12

public boolean onGenericMotionEvent (MotionEvent event)

Implement this method to handle generic motion events.

Generic motion events describe joystick movements, mouse hovers, track pad touches, scroll wheel movements and other input events. The source of the motion event specifies the class of input that was received. Implementations of this method must examine the bits in the source before processing the event. The following code example shows how this is done.

Generic motion events with source class InputDevice#SOURCE_CLASS_POINTER are delivered to the view under the pointer. All other generic motion events are delivered to the focused view.

 public boolean onGenericMotionEvent(MotionEvent event) {
     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
         if (event.getAction() == MotionEvent.ACTION_MOVE) {
             // process the joystick movement...
             return true;
         }
     }
     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
         switch (event.getAction()) {
             case MotionEvent.ACTION_HOVER_MOVE:
                 // process the mouse hover movement...
                 return true;
             case MotionEvent.ACTION_SCROLL:
                 // process the scroll wheel movement...
                 return true;
         }
     }
     return super.onGenericMotionEvent(event);
 }
Parameters
event MotionEvent: The generic motion event being processed.
Returns
boolean True if the event was handled, false otherwise.

onKeyDown

Added in API level 1

public boolean onKeyDown (int keyCode, 
                KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyDown(): perform press of the view when KeyEvent#KEYCODE_DPAD_CENTER or KeyEvent#KEYCODE_ENTER is released, if the view is enabled and clickable.

Key presses in software keyboards will generally NOT trigger this listener, although some may elect to do so in some situations. Do not rely on this to catch software key presses.

Parameters
keyCode int: a key code that represents the button pressed, from KeyEvent
event KeyEvent: the KeyEvent object that defines the button action
Returns
boolean If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

onKeyMultiple

Added in API level 1

public boolean onKeyMultiple (int keyCode, 
                int repeatCount, 
                KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handle the event).

Key presses in software keyboards will generally NOT trigger this listener, although some may elect to do so in some situations. Do not rely on this to catch software key presses.

Parameters
keyCode int: A key code that represents the button pressed, from KeyEvent.
repeatCount int: The number of times the action was made.
event KeyEvent: The KeyEvent object that defines the button action.
Returns
boolean If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

onKeyPreIme

Added in API level 3

public boolean onKeyPreIme (int keyCode, 
                KeyEvent event)

Handle a key event before it is processed by any input method associated with the view hierarchy. This can be used to intercept key events in special situations before the IME consumes them; a typical example would be handling the BACK key to update the application's UI instead of allowing the IME to see it and close itself.

Parameters
keyCode int: The value in event.getKeyCode().
event KeyEvent: Description of the key event.
Returns
boolean If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

onKeyShortcut

Added in API level 1

public boolean onKeyShortcut (int keyCode, 
                KeyEvent event)

Called on the focused view when a key shortcut event is not handled. Override this method to implement local key shortcuts for the View. Key shortcuts can also be implemented by setting the shortcut property of menu items.

Parameters
keyCode int: The value in event.getKeyCode().
event KeyEvent: Description of the key event.
Returns
boolean If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

onKeyUp

Added in API level 1

public boolean onKeyUp (int keyCode, 
                KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyUp(): perform clicking of the view when KeyEvent#KEYCODE_DPAD_CENTER, KeyEvent#KEYCODE_ENTER or KeyEvent#KEYCODE_SPACE is released.

Key presses in software keyboards will generally NOT trigger this listener, although some may elect to do so in some situations. Do not rely on this to catch software key presses.

Parameters
keyCode int: A key code that represents the button pressed, from KeyEvent.
event KeyEvent: The KeyEvent object that defines the button action.
Returns
boolean If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

onPreDraw

Added in API level 1

public boolean onPreDraw ()

Callback method to be invoked when the view tree is about to be drawn. At this point, all views in the tree have been measured and given a frame. Clients can use this to adjust their scroll bounds or even to request a new layout before drawing occurs.

Returns
boolean Return true to proceed with the current drawing pass, or false to cancel.

onPrivateIMECommand

Added in API level 3

public boolean onPrivateIMECommand (String action, 
                Bundle data)

Called by the framework in response to a private command from the current method, provided by it calling InputConnection.performPrivateCommand().

Parameters
action String: The action name of the command.
data Bundle: Any additional data for the command. This may be null.
Returns
boolean Return true if you handled the command, else false.

onReceiveContent

Added in API level 31

public ContentInfo onReceiveContent (ContentInfo payload)

Default TextView implementation for receiving content. Apps wishing to provide custom behavior should configure a listener via View.setOnReceiveContentListener(String[], OnReceiveContentListener).

For non-editable TextViews the default behavior is a no-op (returns the passed-in content without acting on it).

For editable TextViews the default behavior is to insert text into the view, coercing non-text content to text as needed. The MIME types "text/plain" and "text/html" have well-defined behavior for this, while other MIME types have reasonable fallback behavior (see ClipData.Item#coerceToStyledText).

Parameters
payload ContentInfo: The content to insert and related metadata. This value cannot be null.
Returns
ContentInfo The portion of the passed-in content that was not handled (may be all, some, or none of the passed-in content). This value may be null.

onResolvePointerIcon

Added in API level 24

public PointerIcon onResolvePointerIcon (MotionEvent event, 
                int pointerIndex)

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 MotionEvent: The MotionEvent from a mouse
pointerIndex int: The index of the pointer for which to retrieve the PointerIcon. This will be between 0 and MotionEvent#getPointerCount().
Returns
PointerIcon

onRestoreInstanceState

Added in API level 1

public void onRestoreInstanceState (Parcelable state)

Hook allowing a view to re-apply a representation of its internal state that had previously been generated by onSaveInstanceState(). This function will never be called with a null state.
If you override this method you must call through to the superclass implementation.

Parameters
state Parcelable: The frozen state that had previously been returned by onSaveInstanceState().

onRtlPropertiesChanged

Added in API level 17

public 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 int: the direction of the layout Value is View.LAYOUT_DIRECTION_LTR, or View.LAYOUT_DIRECTION_RTL

onSaveInstanceState

Added in API level 1

public Parcelable onSaveInstanceState ()

Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

Some examples of things you may store here: the current cursor position in a text view (but usually not the text itself since that is stored in a content provider or other persistent storage), the currently selected item in a list view.
If you override this method you must call through to the superclass implementation.

Returns
Parcelable Returns a Parcelable object containing the view's current dynamic state, or null if there is nothing interesting to save.

onScreenStateChanged

Added in API level 16

public void onScreenStateChanged (int screenState)

This method is called whenever the state of the screen this view is attached to changes. A state change will usually occurs when the screen turns on or off (whether it happens automatically or the user does it manually.)

Parameters
screenState int: The new state of the screen. Can be either View.SCREEN_STATE_ON or View.SCREEN_STATE_OFF

onTextContextMenuItem

Added in API level 3

public boolean onTextContextMenuItem (int id)

Called when a context menu option for the text view is selected. Currently this will be one of R.id.selectAll, R.id.cut, R.id.copy, R.id.paste, R.id.pasteAsPlainText (starting at API level 23) or R.id.shareText.

Parameters
id int
Returns
boolean true if the context menu item action was performed.

onTouchEvent

Added in API level 1

public boolean onTouchEvent (MotionEvent event)

Implement this method to handle touch screen motion events.

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

  • obeying click sound preferences
  • dispatching OnClickListener calls
  • handling ACTION_CLICK when accessibility features are enabled
Parameters
event MotionEvent: The motion event.
Returns
boolean True if the event was handled, false otherwise.

onTrackballEvent

Added in API level 1

public boolean onTrackballEvent (MotionEvent event)

Implement this method to handle trackball motion events. The relative movement of the trackball since the last event can be retrieve with MotionEvent.getX() and MotionEvent.getY(). These are normalized so that a movement of 1 corresponds to the user pressing one DPAD key (so they will often be fractional values, representing the more fine-grained movement information available from a trackball).

Parameters
event MotionEvent: The motion event.
Returns
boolean True if the event was handled, false otherwise.

onVisibilityAggregated

Added in API level 24

public void onVisibilityAggregated (boolean isVisible)

Called when the user-visibility of this View is potentially affected by a change to this view itself, an ancestor view or the window this view is attached to.
If you override this method you must call through to the superclass implementation.

Parameters
isVisible boolean: true if this view and all of its ancestors are View.VISIBLE and this view's window is also visible

onWindowFocusChanged

Added in API level 1

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 boolean: True if the window containing this view now has focus, false otherwise.

performLongClick

Added in API level 1

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
boolean true if one of the above receivers consumed the event, false otherwise

removeTextChangedListener

Added in API level 1

public void removeTextChangedListener (TextWatcher watcher)

Removes the specified TextWatcher from the list of those whose methods are called whenever this TextView's text changes.

Parameters
watcher TextWatcher

sendAccessibilityEventUnchecked

Added in API level 4

public void sendAccessibilityEventUnchecked (AccessibilityEvent event)

This method behaves exactly as sendAccessibilityEvent(int) but takes as an argument an empty AccessibilityEvent and does not perform a check whether accessibility is enabled.

If an AccessibilityDelegate has been specified via calling setAccessibilityDelegate(android.view.View.AccessibilityDelegate) its AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent) is responsible for handling this call.

Parameters
event AccessibilityEvent: The event to send.

setAllCaps

Added in API level 14

public void setAllCaps (boolean allCaps)

Sets the properties of this field to transform input to ALL CAPS display. This may use a "small caps" formatting if available. This setting will be ignored if this field is editable or selectable. This call replaces the current transformation method. Disabling this will not necessarily restore the previous behavior from before this was enabled.

Related XML Attributes:

  • android:textAllCaps
Parameters
allCaps boolean

See also:

  • setTransformationMethod(TransformationMethod)

setAutoLinkMask

Added in API level 1

public final void setAutoLinkMask (int mask)

Sets the autolink mask of the text. See Linkify.ALL and peers for possible values.

Note: Linkify.MAP_ADDRESSES is deprecated and should be avoided; see its documentation.

Related XML Attributes:

  • android:autoLink
Parameters
mask int

setAutoSizeTextTypeUniformWithConfiguration

Added in API level 26

public void setAutoSizeTextTypeUniformWithConfiguration (int autoSizeMinTextSize, 
                int autoSizeMaxTextSize, 
                int autoSizeStepGranularity, 
                int unit)

Specify whether this widget should automatically scale the text to try to perfectly fit within the layout bounds. If all the configuration params are valid the type of auto-size is set to AUTO_SIZE_TEXT_TYPE_UNIFORM.

Related XML Attributes:

  • android:autoSizeTextType
  • android:autoSizeMinTextSize
  • android:autoSizeMaxTextSize
  • android:autoSizeStepGranularity
Parameters
autoSizeMinTextSize int: the minimum text size available for auto-size
autoSizeMaxTextSize int: the maximum text size available for auto-size
autoSizeStepGranularity int: the auto-size step granularity. It is used in conjunction with the minimum and maximum text size in order to build the set of text sizes the system uses to choose from when auto-sizing
unit int: the desired dimension unit for all sizes above. See TypedValue for the possible dimension units
Throws
IllegalArgumentException if any of the configuration params are invalid.

See also:

  • setAutoSizeTextTypeWithDefaults(int)
  • setAutoSizeTextTypeUniformWithPresetSizes(int[], int)
  • getAutoSizeMinTextSize()
  • getAutoSizeMaxTextSize()
  • getAutoSizeStepGranularity()
  • getAutoSizeTextAvailableSizes()

setAutoSizeTextTypeUniformWithPresetSizes

Added in API level 26

public void setAutoSizeTextTypeUniformWithPresetSizes (int[] presetSizes, 
                int unit)

Specify whether this widget should automatically scale the text to try to perfectly fit within the layout bounds. If at least one value from the presetSizes is valid then the type of auto-size is set to AUTO_SIZE_TEXT_TYPE_UNIFORM.

Related XML Attributes:

  • android:autoSizeTextType
  • android:autoSizePresetSizes
Parameters
presetSizes int: an int array of sizes in pixels This value cannot be null.
unit int: the desired dimension unit for the preset sizes above. See TypedValue for the possible dimension units
Throws
IllegalArgumentException if all of the presetSizes are invalid.

See also:

  • setAutoSizeTextTypeWithDefaults(int)
  • setAutoSizeTextTypeUniformWithConfiguration(int, int, int, int)
  • getAutoSizeMinTextSize()
  • getAutoSizeMaxTextSize()
  • getAutoSizeTextAvailableSizes()

setAutoSizeTextTypeWithDefaults

Added in API level 26

public void setAutoSizeTextTypeWithDefaults (int autoSizeTextType)

Specify whether this widget should automatically scale the text to try to perfectly fit within the layout bounds by using the default auto-size configuration.

Related XML Attributes:

  • android:autoSizeTextType
Parameters
autoSizeTextType int: the type of auto-size. Must be one of TextView#AUTO_SIZE_TEXT_TYPE_NONE or TextView#AUTO_SIZE_TEXT_TYPE_UNIFORM Value is AUTO_SIZE_TEXT_TYPE_NONE, or AUTO_SIZE_TEXT_TYPE_UNIFORM
Throws
IllegalArgumentException if autoSizeTextType is none of the types above.

See also:

  • getAutoSizeTextType()

setBreakStrategy

Added in API level 23

public void setBreakStrategy (int breakStrategy)

Sets the break strategy for breaking paragraphs into lines. The default value for TextView is Layout#BREAK_STRATEGY_HIGH_QUALITY, and the default value for EditText is Layout#BREAK_STRATEGY_SIMPLE, the latter to avoid the text "dancing" when being edited.

Enabling hyphenation with either using Layout#HYPHENATION_FREQUENCY_NORMAL or Layout#HYPHENATION_FREQUENCY_FULL while line breaking is set to one of Layout#BREAK_STRATEGY_BALANCED, Layout#BREAK_STRATEGY_HIGH_QUALITY improves the structure of text layout however has performance impact and requires more time to do the text layout.

Compared with setLineBreakStyle(int), line break style with different strictness is evaluated in the ICU to identify the potential breakpoints. In setBreakStrategy(int), line break strategy handles the post processing of ICU's line break result. It aims to evaluate ICU's breakpoints and break the lines based on the constraint.

Related XML Attributes:

  • android:breakStrategy
Parameters
breakStrategy int: Value is LineBreaker.BREAK_STRATEGY_SIMPLE, LineBreaker.BREAK_STRATEGY_HIGH_QUALITY, or LineBreaker.BREAK_STRATEGY_BALANCED

See also:

  • getBreakStrategy()
  • setHyphenationFrequency(int)

setCompoundDrawablePadding

Added in API level 1

public void setCompoundDrawablePadding (int pad)

Sets the size of the padding between the compound drawables and the text.

Related XML Attributes:

  • android:drawablePadding
Parameters
pad int

setCompoundDrawableTintBlendMode

Added in API level 29

public void setCompoundDrawableTintBlendMode (BlendMode blendMode)

Specifies the blending mode used to apply the tint specified by setCompoundDrawableTintList(android.content.res.ColorStateList) to the compound drawables. The default mode is PorterDuff.Mode#SRC_IN.

Related XML Attributes:

  • android:drawableTintMode
Parameters
blendMode BlendMode: the blending mode used to apply the tint, may be null to clear tint

See also:

  • setCompoundDrawableTintList(ColorStateList)
  • Drawable.setTintBlendMode(BlendMode)

setCompoundDrawableTintList

Added in API level 23

public void setCompoundDrawableTintList (ColorStateList tint)

Applies a tint to the compound drawables. Does not modify the current tint mode, which is BlendMode#SRC_IN by default.

Subsequent calls to setCompoundDrawables(android.graphics.drawable.Drawable, android.graphics.drawable.Drawable, android.graphics.drawable.Drawable, android.graphics.drawable.Drawable) and related methods will automatically mutate the drawables and apply the specified tint and tint mode using Drawable#setTintList(ColorStateList).

Related XML Attributes:

  • android:drawableTint
Parameters
tint ColorStateList: the tint to apply, may be null to clear tint

See also:

  • getCompoundDrawableTintList()
  • Drawable.setTintList(ColorStateList)

setCompoundDrawableTintMode

Added in API level 23

public void setCompoundDrawableTintMode (PorterDuff.Mode tintMode)

Specifies the blending mode used to apply the tint specified by setCompoundDrawableTintList(android.content.res.ColorStateList) to the compound drawables. The default mode is PorterDuff.Mode#SRC_IN.

Related XML Attributes:

  • android:drawableTintMode
Parameters
tintMode PorterDuff.Mode: the blending mode used to apply the tint, may be null to clear tint

See also:

  • setCompoundDrawableTintList(ColorStateList)
  • Drawable.setTintMode(PorterDuff.Mode)

setCompoundDrawables

Added in API level 1

public void setCompoundDrawables (Drawable left, 
                Drawable top, 
                Drawable right, 
                Drawable bottom)

Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text. Use null if you do not want a Drawable there. The Drawables must already have had Drawable#setBounds called.

Calling this method will overwrite any Drawables previously set using setCompoundDrawablesRelative(Drawable, Drawable, Drawable, Drawable) or related methods.

Related XML Attributes:

  • android:drawableLeft
  • android:drawableTop
  • android:drawableRight
  • android:drawableBottom
Parameters
left Drawable: This value may be null.
top Drawable: This value may be null.
right Drawable: This value may be null.
bottom Drawable: This value may be null.

setCompoundDrawablesRelative

Added in API level 17

public void setCompoundDrawablesRelative (Drawable start, 
                Drawable top, 
                Drawable end, 
                Drawable bottom)

Sets the Drawables (if any) to appear to the start of, above, to the end of, and below the text. Use null if you do not want a Drawable there. The Drawables must already have had Drawable#setBounds called.

Calling this method will overwrite any Drawables previously set using setCompoundDrawables(Drawable, Drawable, Drawable, Drawable) or related methods.

Related XML Attributes:

  • android:drawableStart
  • android:drawableTop
  • android:drawableEnd
  • android:drawableBottom
Parameters
start Drawable: This value may be null.
top Drawable: This value may be null.
end Drawable: This value may be null.
bottom Drawable: This value may be null.

setCompoundDrawablesRelativeWithIntrinsicBounds

Added in API level 17

public void setCompoundDrawablesRelativeWithIntrinsicBounds (Drawable start, 
                Drawable top, 
                Drawable end, 
                Drawable bottom)

Sets the Drawables (if any) to appear to the start of, above, to the end of, and below the text. Use null if you do not want a Drawable there. The Drawables' bounds will be set to their intrinsic bounds.

Calling this method will overwrite any Drawables previously set using setCompoundDrawables(Drawable, Drawable, Drawable, Drawable) or related methods.

Related XML Attributes:

  • android:drawableStart
  • android:drawableTop
  • android:drawableEnd
  • android:drawableBottom
Parameters
start Drawable: This value may be null.
top Drawable: This value may be null.
end Drawable: This value may be null.
bottom Drawable: This value may be null.

setCompoundDrawablesRelativeWithIntrinsicBounds

Added in API level 17

public void setCompoundDrawablesRelativeWithIntrinsicBounds (int start, 
                int top, 
                int end, 
                int bottom)

Sets the Drawables (if any) to appear to the start of, above, to the end of, and below the text. Use 0 if you do not want a Drawable there. The Drawables' bounds will be set to their intrinsic bounds.

Calling this method will overwrite any Drawables previously set using setCompoundDrawables(Drawable, Drawable, Drawable, Drawable) or related methods.

Related XML Attributes:

  • android:drawableStart
  • android:drawableTop
  • android:drawableEnd
  • android:drawableBottom
Parameters
start int: Resource identifier of the start Drawable.
top int: Resource identifier of the top Drawable.
end int: Resource identifier of the end Drawable.
bottom int: Resource identifier of the bottom Drawable.

setCompoundDrawablesWithIntrinsicBounds

Added in API level 1

public void setCompoundDrawablesWithIntrinsicBounds (Drawable left, 
                Drawable top, 
                Drawable right, 
                Drawable bottom)

Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text. Use null if you do not want a Drawable there. The Drawables' bounds will be set to their intrinsic bounds.

Calling this method will overwrite any Drawables previously set using setCompoundDrawablesRelative(Drawable, Drawable, Drawable, Drawable) or related methods.

Related XML Attributes:

  • android:drawableLeft
  • android:drawableTop
  • android:drawableRight
  • android:drawableBottom
Parameters
left Drawable: This value may be null.
top Drawable: This value may be null.
right Drawable: This value may be null.
bottom Drawable: This value may be null.

setCompoundDrawablesWithIntrinsicBounds

Added in API level 3

public void setCompoundDrawablesWithIntrinsicBounds (int left, 
                int top, 
                int right, 
                int bottom)

Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text. Use 0 if you do not want a Drawable there. The Drawables' bounds will be set to their intrinsic bounds.

Calling this method will overwrite any Drawables previously set using setCompoundDrawablesRelative(Drawable, Drawable, Drawable, Drawable) or related methods.

Related XML Attributes:

  • android:drawableLeft
  • android:drawableTop
  • android:drawableRight
  • android:drawableBottom
Parameters
left int: Resource identifier of the left Drawable.
top int: Resource identifier of the top Drawable.
right int: Resource identifier of the right Drawable.
bottom int: Resource identifier of the bottom Drawable.

setCursorVisible

Added in API level 1

public void setCursorVisible (boolean visible)

Set whether the cursor is visible. The default is true. Note that this property only makes sense for editable TextView. If IME is consuming the input, the cursor will always be invisible, visibility will be updated as the last state when IME does not consume the input anymore.

Related XML Attributes:

  • android:cursorVisible
Parameters
visible boolean

See also:

  • isCursorVisible()

setCustomInsertionActionModeCallback

Added in API level 23

public void setCustomInsertionActionModeCallback (ActionMode.Callback actionModeCallback)

If provided, this ActionMode.Callback will be used to create the ActionMode when text insertion is initiated in this View. The standard implementation populates the menu with a subset of Select All, Paste and Replace actions, depending on what this View supports.

A custom implementation can add new entries in the default menu in its ActionMode.Callback.onPrepareActionMode(android.view.ActionMode, android.view.Menu) method. The default actions can also be removed from the menu using Menu.removeItem(int) and passing R.id.selectAll, R.id.paste, R.id.pasteAsPlainText (starting at API level 23) or R.id.replaceText ids as parameters.

Returning false from ActionMode.Callback.onCreateActionMode(android.view.ActionMode, android.view.Menu) will prevent the action mode from being started.

Action click events should be handled by the custom implementation of ActionMode.Callback.onActionItemClicked(android.view.ActionMode, android.view.MenuItem).

Note that text insertion mode is not started when a TextView receives focus and the R.attr.selectAllOnFocus flag has been set.

Parameters
actionModeCallback ActionMode.Callback

setCustomSelectionActionModeCallback

Added in API level 11

public void setCustomSelectionActionModeCallback (ActionMode.Callback actionModeCallback)

If provided, this ActionMode.Callback will be used to create the ActionMode when text selection is initiated in this View.

The standard implementation populates the menu with a subset of Select All, Cut, Copy, Paste, Replace and Share actions, depending on what this View supports.

A custom implementation can add new entries in the default menu in its ActionMode.Callback.onPrepareActionMode(ActionMode, android.view.Menu) method. The default actions can also be removed from the menu using Menu.removeItem(int) and passing R.id.selectAll, R.id.cut, R.id.copy, R.id.paste, R.id.pasteAsPlainText (starting at API level 23), R.id.replaceText or R.id.shareText ids as parameters.

Returning false from ActionMode.Callback.onCreateActionMode(ActionMode, android.view.Menu) will prevent the action mode from being started.

Action click events should be handled by the custom implementation of ActionMode.Callback.onActionItemClicked(ActionMode, android.view.MenuItem).

Note that text selection mode is not started when a TextView receives focus and the R.attr.selectAllOnFocus flag has been set. The content is highlighted in that case, to allow for quick replacement.

Parameters
actionModeCallback ActionMode.Callback

setEditableFactory

Added in API level 1

public final void setEditableFactory (Editable.Factory factory)

Sets the Factory used to create new Editables.

Parameters
factory Editable.Factory: Editable.Factory to be used

See also:

  • Editable.Factory
  • TextView.BufferType.EDITABLE

setElegantTextHeight

Added in API level 21

public void setElegantTextHeight (boolean elegant)

Set the TextView's elegant height metrics flag. This setting selects font variants that have not been compacted to fit Latin-based vertical metrics, and also increases top and bottom bounds to provide more space.

Related XML Attributes:

  • android:elegantTextHeight
Parameters
elegant boolean: set the paint's elegant metrics flag.

See also:

  • isElegantTextHeight()
  • Paint.isElegantTextHeight()

setEllipsize

Added in API level 1

public void setEllipsize (TextUtils.TruncateAt where)

Causes words in the text that are longer than the view's width to be ellipsized instead of broken in the middle. You may also want to setSingleLine() or setHorizontallyScrolling(boolean) to constrain the text to a single line. Use null to turn off ellipsizing. If setMaxLines(int) has been used to set two or more lines, only TextUtils.TruncateAt.END and TextUtils.TruncateAt.MARQUEE are supported (other ellipsizing types will not do anything).

Related XML Attributes:

  • android:ellipsize
Parameters
where TextUtils.TruncateAt

setEms

Added in API level 1

public void setEms (int ems)

Sets the width of the TextView to be exactly ems wide. This value is used for width calculation if LayoutParams does not force TextView to have an exact width. Setting this value overrides previous minimum/maximum configurations such as setMinEms(int) or setMaxEms(int).

Related XML Attributes:

  • android:ems
Parameters
ems int: the exact width of the TextView in terms of ems

See also:

  • setWidth(int)

setEnabled

Added in API level 1

public void setEnabled (boolean enabled)

Set the enabled state of this view. The interpretation of the enabled state varies by subclass.

Parameters
enabled boolean: True if this view is enabled, false otherwise.

setError

Added in API level 1

public void setError (CharSequence error)

Sets the right-hand compound drawable of the TextView to the "error" icon and sets an error message that will be displayed in a popup when the TextView has focus. The icon and error message will be reset to null when any key events cause changes to the TextView's text. If the error is null, the error message and icon will be cleared.

Parameters
error CharSequence

setError

Added in API level 1

public void setError (CharSequence error, 
                Drawable icon)

Sets the right-hand compound drawable of the TextView to the specified icon and sets an error message that will be displayed in a popup when the TextView has focus. The icon and error message will be reset to null when any key events cause changes to the TextView's text. The drawable must already have had Drawable#setBounds set on it. If the error is null, the error message will be cleared (and you should provide a null icon as well).

Parameters
error CharSequence
icon Drawable

setExtractedText

Added in API level 3

public void setExtractedText (ExtractedText text)

Apply to this text view the given extracted text, as previously returned by extractText(android.view.inputmethod.ExtractedTextRequest, android.view.inputmethod.ExtractedText).

Parameters
text ExtractedText

setFallbackLineSpacing

Added in API level 28

public void setFallbackLineSpacing (boolean enabled)

Set whether to respect the ascent and descent of the fallback fonts that are used in displaying the text (which is needed to avoid text from consecutive lines running into each other). If set, fallback fonts that end up getting used can increase the ascent and descent of the lines that they are used on.

It is required to be true if text could be in languages like Burmese or Tibetan where text is typically much taller or deeper than Latin text.

Related XML Attributes:

  • android:fallbackLineSpacing
Parameters
enabled boolean: whether to expand linespacing based on fallback fonts, true by default

See also:

  • StaticLayout.Builder.setUseLineSpacingFromFallbacks(boolean)

setFilters

Added in API level 1

public void setFilters (InputFilter[] filters)

Sets the list of input filters that will be used if the buffer is Editable. Has no effect otherwise.

Related XML Attributes:

  • android:maxLength
Parameters
filters InputFilter

setFirstBaselineToTopHeight

Added in API level 28

public void setFirstBaselineToTopHeight (int firstBaselineToTopHeight)

Updates the top padding of the TextView so that firstBaselineToTopHeight is the distance between the top of the TextView and first line's baseline.

Match the primary value activity on the left with its correct definition on the right.

First and last baseline metrics for a TextView.

Note that if FontMetrics.top or FontMetrics.ascent was already greater than firstBaselineToTopHeight, the top padding is not updated. Moreover since this function sets the top padding, if the height of the TextView is less than the sum of top padding, line height and bottom padding, top of the line will be pushed down and bottom will be clipped.

Related XML Attributes:

  • android:firstBaselineToTopHeight
Parameters
firstBaselineToTopHeight int: distance between first baseline to top of the container in pixels This units of this value are pixels. Value is 0 or greater

See also:

  • getFirstBaselineToTopHeight()
  • setLastBaselineToBottomHeight(int)
  • setPadding(int, int, int, int)
  • setPaddingRelative(int, int, int, int)

setFontFeatureSettings

Added in API level 21

public void setFontFeatureSettings (String fontFeatureSettings)

Sets font feature settings. The format is the same as the CSS font-feature-settings attribute: https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop

Related XML Attributes:

  • android:fontFeatureSettings
Parameters
fontFeatureSettings String: font feature settings represented as CSS compatible string This value may be null.

See also:

  • getFontFeatureSettings()
  • Paint.getFontFeatureSettings()

setFontVariationSettings

Added in API level 26

public boolean setFontVariationSettings (String fontVariationSettings)

Sets TrueType or OpenType font variation settings. The settings string is constructed from multiple pairs of axis tag and style values. The axis tag must contain four ASCII characters and must be wrapped with single quotes (U+0027) or double quotes (U+0022). Axis strings that are longer or shorter than four characters, or contain characters outside of U+0020..U+007E are invalid. If a specified axis name is not defined in the font, the settings will be ignored.

Examples,

  • Set font width to 150.
     
       TextView textView = (TextView) findViewById(R.id.textView);
       textView.setFontVariationSettings("'wdth' 150");
     
     
  • Set the font slant to 20 degrees and ask for italic style.
     
       TextView textView = (TextView) findViewById(R.id.textView);
       textView.setFontVariationSettings("'slnt' 20, 'ital' 1");
     
     

Related XML Attributes:

  • android:fontVariationSettings
Parameters
fontVariationSettings String: font variation settings. You can pass null or empty string as no variation settings.
Returns
boolean true if the given settings is effective to at least one font file underlying this TextView. This function also returns true for empty settings string. Otherwise returns false.
Throws
IllegalArgumentException If given string is not a valid font variation settings format.

See also:

  • getFontVariationSettings()
  • FontVariationAxis

setFreezesText

Added in API level 1

public void setFreezesText (boolean freezesText)

Control whether this text view saves its entire text contents when freezing to an icicle, in addition to dynamic state such as cursor position. By default this is false, not saving the text. Set to true if the text in the text view is not being saved somewhere else in persistent storage (such as in a content provider) so that if the view is later thawed the user will not lose their data. For EditText it is always enabled, regardless of the value of the attribute.

Related XML Attributes:

  • android:freezesText
Parameters
freezesText boolean: Controls whether a frozen icicle should include the entire text data: true to include it, false to not.

setGravity

Added in API level 1

public void setGravity (int gravity)

Sets the horizontal alignment of the text and the vertical gravity that will be used when there is extra space in the TextView beyond what is required for the text itself.

Related XML Attributes:

  • android:gravity
Parameters
gravity int

See also:

  • Gravity

setHeight

Added in API level 1

public void setHeight (int pixels)

Sets the height of the TextView to be exactly pixels tall.

This value is used for height calculation if LayoutParams does not force TextView to have an exact height. Setting this value overrides previous minimum/maximum height configurations such as setMinHeight(int) or setMaxHeight(int).

Related XML Attributes:

  • android:height
Parameters
pixels int: the exact height of the TextView in terms of pixels

See also:

  • setLines(int)

setHighlightColor

Added in API level 1

public void setHighlightColor (int color)

Sets the color used to display the selection highlight.

Related XML Attributes:

  • android:textColorHighlight
Parameters
color int

setHint

Added in API level 1

public final void setHint (CharSequence hint)

Sets the text to be displayed when the text of the TextView is empty. Null means to use the normal empty text. The hint does not currently participate in determining the size of the view.

Related XML Attributes:

  • android:hint
Parameters
hint CharSequence

setHint

Added in API level 1

public final void setHint (int resid)

Sets the text to be displayed when the text of the TextView is empty, from a resource.

Related XML Attributes:

  • android:hint
Parameters
resid int

setHintTextColor

Added in API level 1

public final void setHintTextColor (ColorStateList colors)

Sets the color of the hint text.

Related XML Attributes:

  • android:textColorHint
Parameters
colors ColorStateList

See also:

  • getHintTextColors()
  • setHintTextColor(int)
  • setTextColor(ColorStateList)
  • setLinkTextColor(ColorStateList)

setHintTextColor

Added in API level 1

public final void setHintTextColor (int color)

Sets the color of the hint text for all the states (disabled, focussed, selected...) of this TextView.

Related XML Attributes:

  • android:textColorHint
Parameters
color int

See also:

  • setHintTextColor(ColorStateList)
  • getHintTextColors()
  • setTextColor(int)

setHorizontallyScrolling

Added in API level 1

public void setHorizontallyScrolling (boolean whether)

Sets whether the text should be allowed to be wider than the View is. If false, it will be wrapped to the width of the View.

Related XML Attributes:

  • android:scrollHorizontally
Parameters
whether boolean

setHyphenationFrequency

Added in API level 23

public void setHyphenationFrequency (int hyphenationFrequency)

Sets the frequency of automatic hyphenation to use when determining word breaks. The default value for both TextView and EditText is Layout#HYPHENATION_FREQUENCY_NONE. Note that the default hyphenation frequency value is set from the theme.

Enabling hyphenation with either using Layout#HYPHENATION_FREQUENCY_NORMAL or Layout#HYPHENATION_FREQUENCY_FULL while line breaking is set to one of Layout#BREAK_STRATEGY_BALANCED, Layout#BREAK_STRATEGY_HIGH_QUALITY improves the structure of text layout however has performance impact and requires more time to do the text layout.

Note: Before Android Q, in the theme hyphenation frequency is set to Layout#HYPHENATION_FREQUENCY_NORMAL. The default value is changed into Layout#HYPHENATION_FREQUENCY_NONE on Q.

Related XML Attributes:

  • android:hyphenationFrequency
Parameters
hyphenationFrequency int: the hyphenation frequency to use, one of Layout#HYPHENATION_FREQUENCY_NONE, Layout#HYPHENATION_FREQUENCY_NORMAL, Layout#HYPHENATION_FREQUENCY_FULL Value is Layout.HYPHENATION_FREQUENCY_NORMAL, Layout.HYPHENATION_FREQUENCY_NORMAL_FAST, Layout.HYPHENATION_FREQUENCY_FULL, Layout.HYPHENATION_FREQUENCY_FULL_FAST, or Layout.HYPHENATION_FREQUENCY_NONE

See also:

  • getHyphenationFrequency()
  • getBreakStrategy()

setImeActionLabel

Added in API level 3

public void setImeActionLabel (CharSequence label, 
                int actionId)

Change the custom IME action associated with the text view, which will be reported to an IME with EditorInfo#actionLabel and EditorInfo#actionId when it has focus.

Related XML Attributes:

  • android:imeActionLabel
  • android:imeActionId
Parameters
label CharSequence
actionId int

See also:

  • getImeActionLabel()
  • getImeActionId()
  • EditorInfo

setImeHintLocales

Added in API level 24

public void setImeHintLocales (LocaleList hintLocales)

Change "hint" locales associated with the text view, which will be reported to an IME with EditorInfo#hintLocales when it has focus. Starting with Android O, this also causes internationalized listeners to be created (or change locale) based on the first locale in the input locale list.

Note: If you want new "hint" to take effect immediately you need to call InputMethodManager#restartInput(View).

Parameters
hintLocales LocaleList: List of the languages that the user is supposed to switch to no matter what input method subtype is currently used. Set null to clear the current "hint".

See also:

  • getImeHintLocales()
  • EditorInfo.hintLocales

setImeOptions

Added in API level 3

public void setImeOptions (int imeOptions)

Change the editor type integer associated with the text view, which is reported to an Input Method Editor (IME) with EditorInfo#imeOptions when it has focus.

Related XML Attributes:

  • android:imeOptions
Parameters
imeOptions int

See also:

  • getImeOptions()
  • EditorInfo

setIncludeFontPadding

Added in API level 1

public void setIncludeFontPadding (boolean includepad)

Set whether the TextView includes extra top and bottom padding to make room for accents that go above the normal ascent and descent. The default is true.

Related XML Attributes:

  • android:includeFontPadding
Parameters
includepad boolean

See also:

  • getIncludeFontPadding()

setInputExtras

Added in API level 3

public void setInputExtras (int xmlResId)

Set the extra input data of the text, which is the TextBoxAttribute.extras Bundle that will be filled in when creating an input connection. The given integer is the resource identifier of an XML resource holding an <input-extras> XML tree.

Related XML Attributes:

  • android:editorExtras
Parameters
xmlResId int
Throws
IOException
XmlPullParserException

See also:

  • getInputExtras(boolean)
  • EditorInfo.extras

setInputType

Added in API level 3

public void setInputType (int type)

Set the type of the content with a constant as defined for EditorInfo#inputType. This will take care of changing the key listener, by calling setKeyListener(android.text.method.KeyListener), to match the given content type. If the given content type is EditorInfo#TYPE_NULL then a soft keyboard will not be displayed for this text view. Note that the maximum number of displayed lines (see setMaxLines(int)) will be modified if you change the EditorInfo#TYPE_TEXT_FLAG_MULTI_LINE flag of the input type.

Related XML Attributes:

  • android:inputType
Parameters
type int

See also:

  • getInputType()
  • setRawInputType(int)
  • InputType

setJustificationMode

Added in API level 26

public void setJustificationMode (int justificationMode)

Set justification mode. The default value is Layout#JUSTIFICATION_MODE_NONE. If the last line is too short for justification, the last line will be displayed with the alignment set by View.setTextAlignment(int).

Parameters
justificationMode int: Value is LineBreaker.JUSTIFICATION_MODE_NONE, or LineBreaker.JUSTIFICATION_MODE_INTER_WORD
Returns
void Value is LineBreaker.JUSTIFICATION_MODE_NONE, or LineBreaker.JUSTIFICATION_MODE_INTER_WORD

See also:

  • getJustificationMode()

setKeyListener

Added in API level 1

public void setKeyListener (KeyListener input)

Sets the key listener to be used with this TextView. This can be null to disallow user input. Note that this method has significant and subtle interactions with soft keyboards and other input method: see KeyListener.getInputType() for important details. Calling this method will replace the current content type of the text view with the content type returned by the key listener.

Be warned that if you want a TextView with a key listener or movement method not to be focusable, or if you want a TextView without a key listener or movement method to be focusable, you must call View.setFocusable(boolean) again after calling this to get the focusability back the way you want it.

Related XML Attributes:

  • android:numeric
  • android:digits
  • android:phoneNumber
  • android:inputMethod
  • android:capitalize
  • android:autoText
Parameters
input KeyListener

setLastBaselineToBottomHeight

Added in API level 28

public void setLastBaselineToBottomHeight (int lastBaselineToBottomHeight)

Updates the bottom padding of the TextView so that lastBaselineToBottomHeight is the distance between the bottom of the TextView and the last line's baseline.

Match the primary value activity on the left with its correct definition on the right.

First and last baseline metrics for a TextView.

Note that if FontMetrics.bottom or FontMetrics.descent was already greater than lastBaselineToBottomHeight, the bottom padding is not updated. Moreover since this function sets the bottom padding, if the height of the TextView is less than the sum of top padding, line height and bottom padding, bottom of the text will be clipped.

Related XML Attributes:

  • android:lastBaselineToBottomHeight
Parameters
lastBaselineToBottomHeight int: distance between last baseline to bottom of the container in pixels This units of this value are pixels. Value is 0 or greater

See also:

  • getLastBaselineToBottomHeight()
  • setFirstBaselineToTopHeight(int)
  • setPadding(int, int, int, int)
  • setPaddingRelative(int, int, int, int)

setLetterSpacing

Added in API level 21

public void setLetterSpacing (float letterSpacing)

Sets text letter-spacing in em units. Typical values for slight expansion will be around 0.05. Negative values tighten text.

Related XML Attributes:

  • android:letterSpacing
Parameters
letterSpacing float: A text letter-space value in ems.

See also:

  • getLetterSpacing()
  • Paint.getLetterSpacing()

setLineBreakStyle

Added in API level 33

public void setLineBreakStyle (int lineBreakStyle)

Sets the line-break style for text wrapping.

Line-break style specifies the line-break strategies that can be used for text wrapping. The line-break style affects rule-based line breaking by specifying the strictness of line-breaking rules.

The following are types of line-break styles:

  • LineBreakConfig#LINE_BREAK_STYLE_LOOSE
  • LineBreakConfig#LINE_BREAK_STYLE_NORMAL
  • LineBreakConfig#LINE_BREAK_STYLE_STRICT

The default line-break style is LineBreakConfig#LINE_BREAK_STYLE_NONE, which specifies that no line-breaking rules are used.

See the line-break property for more information.

Parameters
lineBreakStyle int: The line-break style for the text. Value is LineBreakConfig.LINE_BREAK_STYLE_NONE, LineBreakConfig.LINE_BREAK_STYLE_LOOSE, LineBreakConfig.LINE_BREAK_STYLE_NORMAL, or LineBreakConfig.LINE_BREAK_STYLE_STRICT

setLineBreakWordStyle

Added in API level 33

public void setLineBreakWordStyle (int lineBreakWordStyle)

Sets the line-break word style for text wrapping.

The line-break word style affects dictionary-based line breaking by providing phrase-based line-breaking opportunities. Use LineBreakConfig#LINE_BREAK_WORD_STYLE_PHRASE to specify phrase-based line breaking.

The default line-break word style is LineBreakConfig#LINE_BREAK_WORD_STYLE_NONE, which specifies that no line-breaking word style is used.

See the word-break property for more information.

Parameters
lineBreakWordStyle int: The line-break word style for the text. Value is LineBreakConfig.LINE_BREAK_WORD_STYLE_NONE, or LineBreakConfig.LINE_BREAK_WORD_STYLE_PHRASE

setLineHeight

Added in API level 28

public void setLineHeight (int lineHeight)

Sets an explicit line height for this TextView. This is equivalent to the vertical distance between subsequent baselines in the TextView.

Related XML Attributes:

  • android:lineHeight
Parameters
lineHeight int: the line height in pixels This units of this value are pixels. Value is 0 or greater

See also:

  • setLineSpacing(float, float)
  • getLineSpacingExtra()

setLineSpacing

Added in API level 1

public void setLineSpacing (float add, 
                float mult)

Sets line spacing for this TextView. Each line other than the last line will have its height multiplied by mult and have add added to it.

Related XML Attributes:

  • android:lineSpacingExtra
  • android:lineSpacingMultiplier
Parameters
add float: The value in pixels that should be added to each line other than the last line. This will be applied after the multiplier
mult float: The value by which each line height other than the last line will be multiplied by

setLines

Added in API level 1

public void setLines (int lines)

Sets the height of the TextView to be exactly lines tall.

This value is used for height calculation if LayoutParams does not force TextView to have an exact height. Setting this value overrides previous minimum/maximum height configurations such as setMinLines(int) or setMaxLines(int). setSingleLine() will set this value to 1.

Related XML Attributes:

  • android:lines
Parameters
lines int: the exact height of the TextView in terms of lines

See also:

  • setHeight(int)

setLinkTextColor

Added in API level 1

public final void setLinkTextColor (ColorStateList colors)

Sets the color of links in the text.

Related XML Attributes:

  • android:textColorLink
Parameters
colors ColorStateList

See also:

  • setLinkTextColor(int)
  • getLinkTextColors()
  • setTextColor(ColorStateList)
  • setHintTextColor(ColorStateList)

setLinkTextColor

Added in API level 1

public final void setLinkTextColor (int color)

Sets the color of links in the text.

Related XML Attributes:

  • android:textColorLink
Parameters
color int

See also:

  • setLinkTextColor(ColorStateList)
  • getLinkTextColors()

setLinksClickable

Added in API level 1

public final void setLinksClickable (boolean whether)

Sets whether the movement method will automatically be set to LinkMovementMethod if setAutoLinkMask(int) has been set to nonzero and links are detected in setText(char[], int, int). The default is true.

Related XML Attributes:

  • android:linksClickable
Parameters
whether boolean

setMarqueeRepeatLimit

Added in API level 2

public void setMarqueeRepeatLimit (int marqueeLimit)

Sets how many times to repeat the marquee animation. Only applied if the TextView has marquee enabled. Set to -1 to repeat indefinitely.

Related XML Attributes:

  • android:marqueeRepeatLimit
Parameters
marqueeLimit int

See also:

  • getMarqueeRepeatLimit()

setMaxEms

Added in API level 1

public void setMaxEms (int maxEms)

Sets the width of the TextView to be at most maxEms wide.

This value is used for width calculation if LayoutParams does not force TextView to have an exact width. Setting this value overrides previous maximum width configurations such as setMaxWidth(int) or setWidth(int).

Related XML Attributes:

  • android:maxEms
Parameters
maxEms int: the maximum width of TextView in terms of ems

See also:

  • getMaxEms()
  • setEms(int)

setMaxHeight

Added in API level 1

public void setMaxHeight (int maxPixels)

Sets the height of the TextView to be at most maxPixels tall.

This value is used for height calculation if LayoutParams does not force TextView to have an exact height. Setting this value overrides previous maximum height configurations such as setMaxLines(int) or setLines(int).

Related XML Attributes:

  • android:maxHeight
Parameters
maxPixels int: the maximum height of TextView in terms of pixels

See also:

  • getMaxHeight()
  • setHeight(int)

setMaxLines

Added in API level 1

public void setMaxLines (int maxLines)

Sets the height of the TextView to be at most maxLines tall.

This value is used for height calculation if LayoutParams does not force TextView to have an exact height. Setting this value overrides previous maximum height configurations such as setMaxHeight(int) or setLines(int).

Related XML Attributes:

  • android:maxLines
Parameters
maxLines int: the maximum height of TextView in terms of number of lines

See also:

  • getMaxLines()
  • setLines(int)

setMaxWidth

Added in API level 1

public void setMaxWidth (int maxPixels)

Sets the width of the TextView to be at most maxPixels wide.

This value is used for width calculation if LayoutParams does not force TextView to have an exact width. Setting this value overrides previous maximum width configurations such as setMaxEms(int) or setEms(int).

Related XML Attributes:

  • android:maxWidth
Parameters
maxPixels int: the maximum width of TextView in terms of pixels

See also:

  • getMaxWidth()
  • setWidth(int)

setMinEms

Added in API level 1

public void setMinEms (int minEms)

Sets the width of the TextView to be at least minEms wide.

This value is used for width calculation if LayoutParams does not force TextView to have an exact width. Setting this value overrides previous minimum width configurations such as setMinWidth(int) or setWidth(int).

Related XML Attributes:

  • android:minEms
Parameters
minEms int: the minimum width of TextView in terms of ems

See also:

  • getMinEms()
  • setEms(int)

setMinHeight

Added in API level 1

public void setMinHeight (int minPixels)

Sets the height of the TextView to be at least minPixels tall.

This value is used for height calculation if LayoutParams does not force TextView to have an exact height. Setting this value overrides previous minimum height configurations such as setMinLines(int) or setLines(int).

The value given here is different than View.setMinimumHeight(int). Between minHeight and the value set in View.setMinimumHeight(int), the greater one is used to decide the final height.

Related XML Attributes:

  • android:minHeight
Parameters
minPixels int: the minimum height of TextView in terms of pixels

See also:

  • getMinHeight()
  • setHeight(int)

setMinLines

Added in API level 1

public void setMinLines (int minLines)

Sets the height of the TextView to be at least minLines tall.

This value is used for height calculation if LayoutParams does not force TextView to have an exact height. Setting this value overrides other previous minimum height configurations such as setMinHeight(int) or setHeight(int). setSingleLine() will set this value to 1.

Related XML Attributes:

  • android:minLines
Parameters
minLines int: the minimum height of TextView in terms of number of lines

See also:

  • getMinLines()
  • setLines(int)

setMinWidth

Added in API level 1

public void setMinWidth (int minPixels)

Sets the width of the TextView to be at least minPixels wide.

This value is used for width calculation if LayoutParams does not force TextView to have an exact width. Setting this value overrides previous minimum width configurations such as setMinEms(int) or setEms(int).

The value given here is different than View.setMinimumWidth(int). Between minWidth and the value set in View.setMinimumWidth(int), the greater one is used to decide the final width.

Related XML Attributes:

  • android:minWidth
Parameters
minPixels int: the minimum width of TextView in terms of pixels

See also:

  • getMinWidth()
  • setWidth(int)

setMovementMethod

Added in API level 1

public final void setMovementMethod (MovementMethod movement)

Sets the MovementMethod for handling arrow key movement for this TextView. This can be null to disallow using the arrow keys to move the cursor or scroll the view.

Be warned that if you want a TextView with a key listener or movement method not to be focusable, or if you want a TextView without a key listener or movement method to be focusable, you must call View.setFocusable(boolean) again after calling this to get the focusability back the way you want it.

Parameters
movement MovementMethod

setOnEditorActionListener

Added in API level 3

public void setOnEditorActionListener (TextView.OnEditorActionListener l)

Set a special listener to be called when an action is performed on the text view. This will be called when the enter key is pressed, or when an action supplied to the IME is selected by the user. Setting this means that the normal hard key event will not insert a newline into the text view, even if it is multi-line; holding down the ALT modifier will, however, allow the user to insert a newline character.

Parameters
l TextView.OnEditorActionListener

setPadding

Added in API level 1

public void setPadding (int left, 
                int top, 
                int right, 
                int bottom)

Sets the padding. The view may add on the space required to display the scrollbars, depending on the style and visibility of the scrollbars. So the values returned from getPaddingLeft(), getPaddingTop(), getPaddingRight() and getPaddingBottom() may be different from the values set in this call.

Parameters
left int: the left padding in pixels
top int: the top padding in pixels
right int: the right padding in pixels
bottom int: the bottom padding in pixels

See also:

  • setFirstBaselineToTopHeight(int)
  • setLastBaselineToBottomHeight(int)

setPaddingRelative

Added in API level 16

public void setPaddingRelative (int start, 
                int top, 
                int end, 
                int bottom)

Sets the relative padding. The view may add on the space required to display the scrollbars, depending on the style and visibility of the scrollbars. So the values returned from getPaddingStart(), getPaddingTop(), getPaddingEnd() and getPaddingBottom() may be different from the values set in this call.

Parameters
start int: the start padding in pixels
top int: the top padding in pixels
end int: the end padding in pixels
bottom int: the bottom padding in pixels

See also:

  • setFirstBaselineToTopHeight(int)
  • setLastBaselineToBottomHeight(int)

setPaintFlags

Added in API level 1

public void setPaintFlags (int flags)

Sets flags on the Paint being used to display the text and reflows the text if they are different from the old flags.

Parameters
flags int

See also:

  • Paint.setFlags(int)

setPrivateImeOptions

Added in API level 3

public void setPrivateImeOptions (String type)

Set the private content type of the text, which is the EditorInfo.privateImeOptions field that will be filled in when creating an input connection.

Related XML Attributes:

  • android:privateImeOptions
Parameters
type String

See also:

  • getPrivateImeOptions()
  • EditorInfo.privateImeOptions

setRawInputType

Added in API level 3

public void setRawInputType (int type)

Directly change the content type integer of the text view, without modifying any other state.

Related XML Attributes:

  • android:inputType
Parameters
type int

See also:

  • setInputType(int)
  • InputType

setScroller

Added in API level 1

public void setScroller (Scroller s)

Sets the Scroller used for producing a scrolling animation

Parameters
s Scroller: A Scroller instance

setSelectAllOnFocus

Added in API level 1

public void setSelectAllOnFocus (boolean selectAllOnFocus)

Set the TextView so that when it takes focus, all the text is selected.

Related XML Attributes:

  • android:selectAllOnFocus
Parameters
selectAllOnFocus boolean

setSelected

Added in API level 1

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 boolean: true if the view must be selected, false otherwise

setShadowLayer

Added in API level 1

public void setShadowLayer (float radius, 
                float dx, 
                float dy, 
                int color)

Gives the text a shadow of the specified blur radius and color, the specified distance from its drawn position.

The text shadow produced does not interact with the properties on view that are responsible for real time shadows, elevation and translationZ.

Related XML Attributes:

  • android:shadowColor
  • android:shadowDx
  • android:shadowDy
  • android:shadowRadius
Parameters
radius float
dx float
dy float
color int

See also:

  • Paint.setShadowLayer(float, float, float, int)

setShowSoftInputOnFocus

Added in API level 21

public final void setShowSoftInputOnFocus (boolean show)

Sets whether the soft input method will be made visible when this TextView gets focused. The default is true.

Parameters
show boolean

setSingleLine

Added in API level 1

public void setSingleLine (boolean singleLine)

If true, sets the properties of this field (number of lines, horizontally scrolling, transformation method) to be for a single-line input; if false, restores these to the default conditions. Note that the default conditions are not necessarily those that were in effect prior this method, and you may want to reset these properties to your custom values. Note that due to performance reasons, by setting single line for the EditText, the maximum text length is set to 5000 if no other character limitation are applied.

Related XML Attributes:

  • android:singleLine
Parameters
singleLine boolean

setSingleLine

Added in API level 1

public void setSingleLine ()

Sets the properties of this field (lines, horizontally scrolling, transformation method) to be for a single-line input.

Related XML Attributes:

  • android:singleLine

setSpannableFactory

Added in API level 1

public final void setSpannableFactory (Spannable.Factory factory)

Sets the Factory used to create new Spannables.

Parameters
factory Spannable.Factory: Spannable.Factory to be used

See also:

  • Spannable.Factory
  • TextView.BufferType.SPANNABLE

setText

Added in API level 1

public final void setText (int resid)

Sets the text to be displayed using a string resource identifier.

Related XML Attributes:

  • android:text
Parameters
resid int: the resource identifier of the string resource to be displayed

See also:

  • setText(CharSequence)

setText

Added in API level 1

public final void setText (CharSequence text)

Sets the text to be displayed. TextView does not accept HTML-like formatting, which you can do with text strings in XML resource files. To style your strings, attach android.text.style.* objects to a SpannableString, or see the Available Resource Types documentation for an example of setting formatted text in the XML resource file.

When required, TextView will use Spannable.Factory to create final or intermediate Spannables. Likewise it will use Editable.Factory to create final or intermediate Editables. If the passed text is a PrecomputedText but the parameters used to create the PrecomputedText mismatches with this TextView, IllegalArgumentException is thrown. To ensure the parameters match, you can call TextView#setTextMetricsParams before calling this.

Related XML Attributes:

  • android:text
Parameters
text CharSequence: text to be displayed
Throws
IllegalArgumentException if the passed text is a PrecomputedText but the parameters used to create the PrecomputedText mismatches with this TextView.

setText

Added in API level 1

public void setText (CharSequence text, 
                TextView.BufferType type)

Sets the text to be displayed and the TextView.BufferType.

When required, TextView will use Spannable.Factory to create final or intermediate Spannables. Likewise it will use Editable.Factory to create final or intermediate Editables. Subclasses overriding this method should ensure that the following post condition holds, in order to guarantee the safety of the view's measurement and layout operations: regardless of the input, after calling #setText both mText and mTransformed will be different from null.

Related XML Attributes:

  • android:text
  • android:bufferType
Parameters
text CharSequence: text to be displayed
type TextView.BufferType: a TextView.BufferType which defines whether the text is stored as a static text, styleable/spannable text, or editable text

See also:

  • setText(CharSequence)
  • TextView.BufferType
  • setSpannableFactory(Spannable.Factory)
  • setEditableFactory(Editable.Factory)

setText

Added in API level 1

public final void setText (int resid, 
                TextView.BufferType type)

Sets the text to be displayed using a string resource identifier and the TextView.BufferType.

When required, TextView will use Spannable.Factory to create final or intermediate Spannables. Likewise it will use Editable.Factory to create final or intermediate Editables.

Related XML Attributes:

  • android:text
  • android:bufferType
Parameters
resid int: the resource identifier of the string resource to be displayed
type TextView.BufferType: a TextView.BufferType which defines whether the text is stored as a static text, styleable/spannable text, or editable text

See also:

  • setText(int)
  • setText(CharSequence)
  • TextView.BufferType
  • setSpannableFactory(Spannable.Factory)
  • setEditableFactory(Editable.Factory)

setText

Added in API level 1

public final void setText (char[] text, 
                int start, 
                int len)

Sets the TextView to display the specified slice of the specified char array. You must promise that you will not change the contents of the array except for right before another call to setText(), since the TextView has no way to know that the text has changed and that it needs to invalidate and re-layout.

Parameters
text char: char array to be displayed
start int: start index in the char array
len int: length of char count after start

setTextAppearance

Added in API level 1
Deprecated in API level 23

public void setTextAppearance (Context context, 
                int resId)

This method was deprecated in API level 23.
Use setTextAppearance(int) instead.

Sets the text color, size, style, hint color, and highlight color from the specified TextAppearance resource.

Parameters
context Context
resId int

setTextAppearance

Added in API level 23

public void setTextAppearance (int resId)

Sets the text appearance from the specified style resource.

Use a framework-defined TextAppearance style like @android:style/TextAppearance.Material.Body1 or see TextAppearance for the set of attributes that can be used in a custom style.

Related XML Attributes:

  • android:textAppearance
Parameters
resId int: the resource identifier of the style to apply

setTextClassifier

Added in API level 26

public void setTextClassifier (TextClassifier textClassifier)

Sets the TextClassifier for this TextView.

Parameters
textClassifier TextClassifier: This value may be null.

setTextColor

Added in API level 1

public void setTextColor (int color)

Sets the text color for all the states (normal, selected, focused) to be this color.

Related XML Attributes:

  • android:textColor
Parameters
color int: A color value in the form 0xAARRGGBB. Do not pass a resource ID. To get a color value from a resource ID, call getColor.

See also:

  • setTextColor(ColorStateList)
  • getTextColors()

setTextColor

Added in API level 1

public void setTextColor (ColorStateList colors)

Sets the text color.

Related XML Attributes:

  • android:textColor
Parameters
colors ColorStateList

See also:

  • setTextColor(int)
  • getTextColors()
  • setHintTextColor(ColorStateList)
  • setLinkTextColor(ColorStateList)

setTextCursorDrawable

Added in API level 29

public void setTextCursorDrawable (Drawable textCursorDrawable)

Sets the Drawable corresponding to the text cursor. The Drawable defaults to the value of the textCursorDrawable attribute. Note that any change applied to the cursor Drawable will not be visible until the cursor is hidden and then drawn again.

Related XML Attributes:

  • android:textCursorDrawable
Parameters
textCursorDrawable Drawable: This value may be null.

See also:

  • setTextCursorDrawable(int)

setTextCursorDrawable

Added in API level 29

public void setTextCursorDrawable (int textCursorDrawable)

Sets the Drawable corresponding to the text cursor. The Drawable defaults to the value of the textCursorDrawable attribute. Note that any change applied to the cursor Drawable will not be visible until the cursor is hidden and then drawn again.

Related XML Attributes:

  • android:textCursorDrawable
Parameters
textCursorDrawable int

See also:

  • setTextCursorDrawable(Drawable)

setTextIsSelectable

Added in API level 11

public void setTextIsSelectable (boolean selectable)

Sets whether the content of this view is selectable by the user. The default is false, meaning that the content is not selectable.

When you use a TextView to display a useful piece of information to the user (such as a contact's address), make it selectable, so that the user can select and copy its content. You can also use set the XML attribute R.styleable.TextView_textIsSelectable to "true".

When you call this method to set the value of textIsSelectable, it sets the flags focusable, focusableInTouchMode, clickable, and longClickable to the same value. These flags correspond to the attributes android:focusable, android:focusableInTouchMode, android:clickable, and android:longClickable. To restore any of these flags to a state you had set previously, call one or more of the following methods: setFocusable(), setFocusableInTouchMode(), setClickable() or setLongClickable().

Parameters
selectable boolean: Whether the content of this TextView should be selectable.

setTextKeepState

Added in API level 1

public final void setTextKeepState (CharSequence text)

Sets the text to be displayed but retains the cursor position. Same as setText(java.lang.CharSequence) except that the cursor position (if any) is retained in the new text.

When required, TextView will use Spannable.Factory to create final or intermediate Spannables. Likewise it will use Editable.Factory to create final or intermediate Editables.

Parameters
text CharSequence: text to be displayed

See also:

  • setText(CharSequence)

setTextKeepState

Added in API level 1

public final void setTextKeepState (CharSequence text, 
                TextView.BufferType type)

Sets the text to be displayed and the TextView.BufferType but retains the cursor position. Same as setText(java.lang.CharSequence, android.widget.TextView.BufferType) except that the cursor position (if any) is retained in the new text.

When required, TextView will use Spannable.Factory to create final or intermediate Spannables. Likewise it will use Editable.Factory to create final or intermediate Editables.

Parameters
text CharSequence: text to be displayed
type TextView.BufferType: a TextView.BufferType which defines whether the text is stored as a static text, styleable/spannable text, or editable text

See also:

  • setText(CharSequence, android.widget.TextView.BufferType)

setTextLocale

Added in API level 17

public void setTextLocale (Locale locale)

Set the default Locale of the text in this TextView to a one-member LocaleList containing just the given Locale.

Parameters
locale Locale: the Locale for drawing text, must not be null.

See also:

  • setTextLocales(LocaleList)

setTextLocales

Added in API level 24

public void setTextLocales (LocaleList locales)

Set the default LocaleList of the text in this TextView to the given value. This value is used to choose appropriate typefaces for ambiguous characters (typically used for CJK locales to disambiguate Hanzi/Kanji/Hanja characters). It also affects other aspects of text display, including line breaking.

Parameters
locales LocaleList: the LocaleList for drawing text, must not be null or empty.

See also:

  • Paint.setTextLocales(LocaleList)

setTextMetricsParams

Added in API level 28

public void setTextMetricsParams (PrecomputedText.Params params)

Apply the text layout parameter. Update the TextView parameters to be compatible with PrecomputedText.Params.

Parameters
params PrecomputedText.Params: This value cannot be null.

See also:

  • PrecomputedText

setTextScaleX

Added in API level 1

public void setTextScaleX (float size)

Sets the horizontal scale factor for text. The default value is 1.0. Values greater than 1.0 stretch the text wider. Values less than 1.0 make the text narrower. By default, this value is 1.0.

Related XML Attributes:

  • android:textScaleX
Parameters
size float: The horizontal scale factor.

setTextSelectHandle

Added in API level 29

public void setTextSelectHandle (int textSelectHandle)

Sets the Drawable corresponding to the selection handle used for positioning the cursor within text. The Drawable defaults to the value of the textSelectHandle attribute. Note that any change applied to the handle Drawable will not be visible until the handle is hidden and then drawn again.

Related XML Attributes:

  • android:textSelectHandle
Parameters
textSelectHandle int

See also:

  • setTextSelectHandle(Drawable)

setTextSelectHandle

Added in API level 29

public void setTextSelectHandle (Drawable textSelectHandle)

Sets the Drawable corresponding to the selection handle used for positioning the cursor within text. The Drawable defaults to the value of the textSelectHandle attribute. Note that any change applied to the handle Drawable will not be visible until the handle is hidden and then drawn again.

Related XML Attributes:

  • android:textSelectHandle
Parameters
textSelectHandle Drawable: This value cannot be null.

See also:

  • setTextSelectHandle(int)

setTextSelectHandleLeft

Added in API level 29

public void setTextSelectHandleLeft (int textSelectHandleLeft)

Sets the Drawable corresponding to the left handle used for selecting text. The Drawable defaults to the value of the textSelectHandleLeft attribute. Note that any change applied to the handle Drawable will not be visible until the handle is hidden and then drawn again.

Related XML Attributes:

  • android:textSelectHandleLeft
Parameters
textSelectHandleLeft int

See also:

  • setTextSelectHandleLeft(Drawable)

setTextSelectHandleLeft

Added in API level 29

public void setTextSelectHandleLeft (Drawable textSelectHandleLeft)

Sets the Drawable corresponding to the left handle used for selecting text. The Drawable defaults to the value of the textSelectHandleLeft attribute. Note that any change applied to the handle Drawable will not be visible until the handle is hidden and then drawn again.

Related XML Attributes:

  • android:textSelectHandleLeft
Parameters
textSelectHandleLeft Drawable: This value cannot be null.

See also:

  • setTextSelectHandleLeft(int)

setTextSelectHandleRight

Added in API level 29

public void setTextSelectHandleRight (Drawable textSelectHandleRight)

Sets the Drawable corresponding to the right handle used for selecting text. The Drawable defaults to the value of the textSelectHandleRight attribute. Note that any change applied to the handle Drawable will not be visible until the handle is hidden and then drawn again.

Related XML Attributes:

  • android:textSelectHandleRight
Parameters
textSelectHandleRight Drawable: This value cannot be null.

See also:

  • setTextSelectHandleRight(int)

setTextSelectHandleRight

Added in API level 29

public void setTextSelectHandleRight (int textSelectHandleRight)

Sets the Drawable corresponding to the right handle used for selecting text. The Drawable defaults to the value of the textSelectHandleRight attribute. Note that any change applied to the handle Drawable will not be visible until the handle is hidden and then drawn again.

Related XML Attributes:

  • android:textSelectHandleRight
Parameters
textSelectHandleRight int

See also:

  • setTextSelectHandleRight(Drawable)

setTextSize

Added in API level 1

public void setTextSize (int unit, 
                float size)

Set the default text size to a given unit and value. See TypedValue for the possible dimension units.

Note: if this TextView has the auto-size feature enabled, then this function is no-op.

Related XML Attributes:

  • android:textSize
Parameters
unit int: The desired dimension unit.
size float: The desired size in the given units.

setTextSize

Added in API level 1

public void setTextSize (float size)

Set the default text size to the given value, interpreted as "scaled pixel" units. This size is adjusted based on the current density and user font size preference.

Note: if this TextView has the auto-size feature enabled, then this function is no-op.

Related XML Attributes:

  • android:textSize
Parameters
size float: The scaled pixel size.

setTransformationMethod

Added in API level 1

public final void setTransformationMethod (TransformationMethod method)

Sets the transformation that is applied to the text that this TextView is displaying.

Related XML Attributes:

  • android:password
  • android:singleLine
Parameters
method TransformationMethod

setTypeface

Added in API level 1

public void setTypeface (Typeface tf)

Sets the typeface and style in which the text should be displayed. Note that not all Typeface families actually have bold and italic variants, so you may need to use setTypeface(android.graphics.Typeface, int) to get the appearance that you actually want.

Related XML Attributes:

  • android:fontFamily
  • android:typeface
  • android:textStyle
Parameters
tf Typeface: This value may be null.

See also:

  • getTypeface()

setTypeface

Added in API level 1

public void setTypeface (Typeface tf, 
                int style)

Sets the typeface and style in which the text should be displayed, and turns on the fake bold and italic bits in the Paint if the Typeface that you provided does not have all the bits in the style that you specified.

Related XML Attributes:

  • android:typeface
  • android:textStyle
Parameters
tf Typeface: This value may be null.
style int: Value is Typeface.NORMAL, Typeface.BOLD, Typeface.ITALIC, or Typeface.BOLD_ITALIC

setWidth

Added in API level 1

public void setWidth (int pixels)

Sets the width of the TextView to be exactly pixels wide.

This value is used for width calculation if LayoutParams does not force TextView to have an exact width. Setting this value overrides previous minimum/maximum width configurations such as setMinWidth(int) or setMaxWidth(int).

Related XML Attributes:

  • android:width
Parameters
pixels int: the exact width of the TextView in terms of pixels

See also:

  • setEms(int)

showContextMenu

Added in API level 1

public boolean showContextMenu ()

Shows the context menu for this view.

Returns
boolean true if the context menu was shown, false otherwise

showContextMenu

Added in API level 24

public boolean showContextMenu (float x, 
                float y)

Shows the context menu for this view anchored to the specified view-relative coordinate.

Parameters
x float: the X coordinate in pixels relative to the view to which the menu should be anchored, or Float#NaN to disable anchoring
y float: the Y coordinate in pixels relative to the view to which the menu should be anchored, or Float#NaN to disable anchoring
Returns
boolean true if the context menu was shown, false otherwise

Protected methods

computeHorizontalScrollRange

Added in API level 1

protected int computeHorizontalScrollRange ()

Compute the horizontal range that the horizontal scrollbar represents.

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

The default range is the drawing width of this view.

Returns
int the total horizontal range represented by the horizontal scrollbar

computeVerticalScrollExtent

Added in API level 1

protected int computeVerticalScrollExtent ()

Compute the vertical extent of the vertical scrollbar's thumb within the vertical range. This value is used to compute the length of the thumb within the scrollbar's track.

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

The default extent is the drawing height of this view.

Returns
int the vertical extent of the scrollbar's thumb

computeVerticalScrollRange

Added in API level 1

protected int computeVerticalScrollRange ()

Compute the vertical range that the vertical scrollbar represents.

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

Returns
int the total vertical range represented by the vertical scrollbar

The default range is the drawing height of this view.

drawableStateChanged

Added in API level 1

protected void drawableStateChanged ()

This function is called whenever the state of the view changes in such a way that it impacts the state of drawables being shown.

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

Be sure to call through to the superclass when overriding this function.
If you override this method you must call through to the superclass implementation.

getBottomPaddingOffset

Added in API level 2

protected int getBottomPaddingOffset ()

Amount by which to extend the bottom fading region. Called only when isPaddingOffsetRequired() returns true.

Returns
int The bottom padding offset in pixels.

getDefaultEditable

Added in API level 1

protected boolean getDefaultEditable ()

Subclasses override this to specify that they have a KeyListener by default even if not specifically called for in the XML options.

Returns
boolean

getDefaultMovementMethod

Added in API level 1

protected MovementMethod getDefaultMovementMethod ()

Subclasses override this to specify a default movement method.

Returns
MovementMethod

getLeftFadingEdgeStrength

Added in API level 1

protected float getLeftFadingEdgeStrength ()

Returns the strength, or intensity, of the left faded edge. The strength is a value between 0.0 (no fade) and 1.0 (full fade). The default implementation returns 0.0 or 1.0 but no value in between. Subclasses should override this method to provide a smoother fade transition when scrolling occurs.

Returns
float the intensity of the left fade as a float between 0.0f and 1.0f

getLeftPaddingOffset

Added in API level 2

protected int getLeftPaddingOffset ()

Amount by which to extend the left fading region. Called only when isPaddingOffsetRequired() returns true.

Returns
int The left padding offset in pixels.

getRightFadingEdgeStrength

Added in API level 1

protected float getRightFadingEdgeStrength ()

Returns the strength, or intensity, of the right faded edge. The strength is a value between 0.0 (no fade) and 1.0 (full fade). The default implementation returns 0.0 or 1.0 but no value in between. Subclasses should override this method to provide a smoother fade transition when scrolling occurs.

Returns
float the intensity of the right fade as a float between 0.0f and 1.0f

getRightPaddingOffset

Added in API level 2

protected int getRightPaddingOffset ()

Amount by which to extend the right fading region. Called only when isPaddingOffsetRequired() returns true.

Returns
int The right padding offset in pixels.

getTopPaddingOffset

Added in API level 2

protected int getTopPaddingOffset ()

Amount by which to extend the top fading region. Called only when isPaddingOffsetRequired() returns true.

Returns
int The top padding offset in pixels.

isPaddingOffsetRequired

Added in API level 2

protected boolean isPaddingOffsetRequired ()

If the View draws content inside its padding and enables fading edges, it needs to support padding offsets. Padding offsets are added to the fading edges to extend the length of the fade so that it covers pixels drawn inside the padding. Subclasses of this class should override this method if they need to draw content inside the padding.

Returns
boolean True if padding offset must be applied, false otherwise.

onAttachedToWindow

Added in API level 1

protected void onAttachedToWindow ()

This is called when the view is attached to a window. At this point it has a Surface and will start drawing. Note that this function is guaranteed to be called before onDraw(android.graphics.Canvas), however it may be called any time before the first onDraw -- including before or after onMeasure(int, int).
If you override this method you must call through to the superclass implementation.

onConfigurationChanged

Added in API level 8

protected void onConfigurationChanged (Configuration newConfig)

Called when the current configuration of the resources being used by the application have changed. You can use this to decide when to reload resources that can changed based on orientation and other configuration characteristics. You only need to use this if you are not relying on the normal Activity mechanism of recreating the activity instance upon a configuration change.

Parameters
newConfig Configuration: The new resource configuration.

onCreateContextMenu

Added in API level 1

protected void onCreateContextMenu (ContextMenu menu)

Views should implement this if the view itself is going to add items to the context menu.

Parameters
menu ContextMenu: the context menu to populate

onCreateDrawableState

Added in API level 1

protected int[] onCreateDrawableState (int extraSpace)

Generate the new Drawable state for this view. This is called by the view system when the cached Drawable state is determined to be invalid. To retrieve the current state, you should use getDrawableState().

Parameters
extraSpace int: 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
int[] Returns an array holding the current Drawable state of the view.

onDraw

Added in API level 1

protected void onDraw (Canvas canvas)

Implement this to do your drawing.

Parameters
canvas Canvas: the canvas on which the background will be drawn

onFocusChanged

Added in API level 1

protected void onFocusChanged (boolean focused, 
                int direction, 
                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.
If you override this method you must call through to the superclass implementation.

Parameters
focused boolean: True if the View has focus; false otherwise.
direction int: The direction focus has moved when requestFocus() is called to give this view focus. Values are View.FOCUS_UP, View.FOCUS_DOWN, View.FOCUS_LEFT, View.FOCUS_RIGHT, View.FOCUS_FORWARD, or View.FOCUS_BACKWARD. It may not always apply, in which case use the default. Value is View.FOCUS_BACKWARD, View.FOCUS_FORWARD, View.FOCUS_LEFT, View.FOCUS_UP, View.FOCUS_RIGHT, or View.FOCUS_DOWN
previouslyFocusedRect Rect: The rectangle, in this view's coordinate system, of the previously focused view. If applicable, this will be passed in as finer grained information about where the focus is coming from (in addition to direction). Will be null otherwise.

onLayout

Added in API level 1

protected void onLayout (boolean changed, 
                int left, 
                int top, 
                int right, 
                int bottom)

Called from layout 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 boolean: This is a new size or position for this view
left int: Left position, relative to parent
top int: Top position, relative to parent
right int: Right position, relative to parent
bottom int: Bottom position, relative to parent

onMeasure

Added in API level 1

protected void onMeasure (int widthMeasureSpec, 
                int heightMeasureSpec)

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

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

If this method is overridden, it is the subclass's responsibility to make sure the measured height and width are at least the view's minimum height and width (getSuggestedMinimumHeight() and getSuggestedMinimumWidth()).

Parameters
widthMeasureSpec int: horizontal space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.
heightMeasureSpec int: vertical space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.

onScrollChanged

Added in API level 1

protected void onScrollChanged (int horiz, 
                int vert, 
                int oldHoriz, 
                int oldVert)

This is called in response to an internal scroll in this view (i.e., the view scrolled its own contents). This is typically as a result of scrollBy(int, int) or scrollTo(int, int) having been called.

Parameters
horiz int: Current horizontal scroll origin.
vert int: Current vertical scroll origin.
oldHoriz int: Previous horizontal scroll origin.
oldVert int: Previous vertical scroll origin.

onSelectionChanged

Added in API level 3

protected void onSelectionChanged (int selStart, 
                int selEnd)

This method is called when the selection has changed, in case any subclasses would like to know.

Note: Always call the super implementation, which informs the accessibility subsystem about the selection change.

If you override this method you must call through to the superclass implementation.

Parameters
selStart int: The new selection start location.
selEnd int: The new selection end location.

onTextChanged

Added in API level 1

protected void onTextChanged (CharSequence text, 
                int start, 
                int lengthBefore, 
                int lengthAfter)

This method is called when the text is changed, in case any subclasses would like to know. Within text, the lengthAfter characters beginning at start have just replaced old text that had length lengthBefore. It is an error to attempt to make changes to text from this callback.

Parameters
text CharSequence: The text the TextView is displaying
start int: The offset of the start of the range of the text that was modified
lengthBefore int: The length of the former text that has been replaced
lengthAfter int: The length of the replacement modified text

onVisibilityChanged

Added in API level 8

protected void onVisibilityChanged (View changedView, 
                int visibility)

Called when the visibility of the view or an ancestor of the view has changed.

Parameters
changedView View: The view whose visibility changed. May be this or an ancestor view. This value cannot be null.
visibility int: The new visibility, one of View.VISIBLE, View.INVISIBLE or View.GONE. Value is View.VISIBLE, View.INVISIBLE, or View.GONE

setFrame

Added in API level 1

protected boolean setFrame (int l, 
                int t, 
                int r, 
                int b)
Parameters
l int
t int
r int
b int
Returns
boolean

verifyDrawable

Added in API level 1

protected boolean verifyDrawable (Drawable who)

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.
If you override this method you must call through to the superclass implementation.

Parameters
who Drawable: This value cannot be null.
Returns
boolean boolean If true then the Drawable is being displayed in the view; else false and it is not allowed to animate.

Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.

Last updated 2022-09-08 UTC.

[{ "type": "thumb-down", "id": "missingTheInformationINeed", "label":"Missing the information I need" },{ "type": "thumb-down", "id": "tooComplicatedTooManySteps", "label":"Too complicated / too many steps" },{ "type": "thumb-down", "id": "outOfDate", "label":"Out of date" },{ "type": "thumb-down", "id": "samplesCodeIssue", "label":"Samples / code issue" },{ "type": "thumb-down", "id": "otherDown", "label":"Other" }] [{ "type": "thumb-up", "id": "easyToUnderstand", "label":"Easy to understand" },{ "type": "thumb-up", "id": "solvedMyProblem", "label":"Solved my problem" },{ "type": "thumb-up", "id": "otherUp", "label":"Other" }]

What includes firm infrastructure Human resource management technology development and procurement?

The support activities include a firm's infrastructure, human resource management, technology development, and procurement. The primary activities include inbound logistics, operations, outbound logistics, marketing and sales, and customer service.

What views a firm as a series of business processes that each add value to the product or service?

The value chain model views the firm as a series or chain of basic activities that add a margin of value to a firm's products or services. These activities can be categorized as either primary activities or support activities.

Which company is using a broad market and low cost strategy?

Broad cost leadership strategy: Companies target a broad market by offering products at prices below their competitors. Amazon is a good example of this strategy. The company eliminates every non-essential that might potentially increase the cost of production so it can offer lower prices.

What is high when it is easy for new competitors to enter a market and low when there are significant entry barriers to joining a market?

Threat of new entrants is high when it is easy for new competitors to enter a market and low when there are are significant entry barriers to entering a market. Rivalry among existing competitors is high when competition is fierce in a market and low when competition is more complacent.