android官方API之TextView

来源:https://developer.android.com/reference/android/widget/TextView

added in API level 1

TextView

public class TextView 
extends View implements ViewTreeObserver.OnPreDrawListener

java.lang.Object
   ↳ android.view.View
     ↳ android.widget.TextView
Known direct subclasses

ButtonCheckedTextViewChronometerDigitalClockEditTextTextClock

Known indirect subclasses

AutoCompleteTextViewCheckBoxCompoundButtonExtractEditTextMultiAutoCompleteTextViewRadioButtonSwitchToggleButton


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 AttributesView 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: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: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: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: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:textIsSelectable Indicates that the content of a non-editable text can be selected. 
android:textScaleX Sets the horizontal scaling factor for the text. 
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

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

Inherited fields

From class android.view.View

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, StringextraDataKey, 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)

Prints information about this view in the log output, with the tag VIEW_LOG_TAG.

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

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.

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 nullif 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 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(CharSequence).

int getSelectionStart()

Convenience for Selection.getSelectionStart(CharSequence).

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.

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.

float getTextSize()
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.

finalTransformationMethod 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 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()
boolean isInputMethodTarget()

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

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 callingInputConnection.commitCorrection().

InputConnection onCreateInputConnection(EditorInfo outAttrs)

Create a new InputConnection for an InputMethod to interact with 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_CENTERKeyEvent.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().

void onProvideAutofillStructure(ViewStructure structure, int flags)

Populates a ViewStructure to fullfil an autofill request.

void onProvideStructure(ViewStructure structure)

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

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 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 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 bysetCompoundDrawableTintList(ColorStateList) to the compound drawables.

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

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, Drawabletop, 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.CallbackactionModeCallback)

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

void setCustomSelectionActionModeCallback(ActionMode.CallbackactionModeCallback)

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(ExtractedTextRequest, 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 equal to the distance between the firt text baseline and the top of this TextView.

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 withEditorInfo.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 equal to the distance between the last text baseline and the bottom of this TextView.

void setLetterSpacing(float letterSpacing)

Sets text letter-spacing in em units.

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

Assign a size and position to this view.

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

From class java.lang.Object

From interface android.graphics.drawable.Drawable.Callback

From interface android.view.KeyEvent.Callback

From interface android.view.accessibility.AccessibilityEventSource

From interface android.view.ViewTreeObserver.OnPreDrawListener

XML attributes

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.

Constant Value Description
all f Match all patterns (equivalent to web|email|phone|map).
email 2 Match email addresses.
map 8 Match map addresses.
none 0 Match no patterns (default).
phone 4 Match phone numbers.
web 1 Match Web URLs.

Related methods:

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:

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:

android:autoSizePresetSizes

Resource array of dimensions to be used in conjunction with autoSizeTextType set to uniform. OverridesautoSizeStepGranularity 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:

android:autoSizeStepGranularity

Specify the auto-size step size if autoSizeTextType is set to uniform. The default is 1px. OverwritesautoSizePresetSizes 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:

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.

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

Related methods:

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:

android:breakStrategy

Break strategy (control over paragraph layout).

Must be one of the following constant values.

Constant Value Description
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:

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.

Constant Value Description
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:

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.

Constant Value Description
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:

android:cursorVisible

Makes the cursor visible (the default) or invisible.

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

Related methods:

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:

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:

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:

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:

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:

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:

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:

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:

android:drawableTintMode

Blending mode used to apply the compound (left, top, etc.) drawables tint.

Must be one of the following constant values.

Constant Value Description
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:

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:

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:

android:elegantTextHeight

Elegant text height, especially for less compacted complex script text.

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

Related methods:

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.

Constant Value Description
end 3  
marquee 4  
middle 2  
none 0  
start 1  

Related methods:

android:ems

Makes the TextView be exactly this many ems wide.

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

Related methods:

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:

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:

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:

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:

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:

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.

Constant Value Description
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:

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:

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:

android:hyphenationFrequency

Frequency of automatic hyphenation.

Must be one of the following constant values.

Constant Value Description
full 2 Standard amount of hyphenation, useful for running text and for screens with limited space for text.
none 0 No hyphenation.
normal 1 Less frequent hyphenation, useful for informal use cases, such as chat messages.

Related methods:

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:

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:

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.

Constant Value Description
actionDone 6 The action key performs a "done" operation, closing the soft input method. Corresponds toEditorInfo.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 TextViewused 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 languagaes 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:

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:

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:

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.

Constant Value Description
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 toInputType.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.
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.
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:

android:justificationMode

Mode for justification.

Must be one of the following constant values.

Constant Value Description
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:

android:letterSpacing

Text letter-spacing.

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

Related methods:

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:

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:

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:

android:lines

Makes the TextView be exactly this many lines tall.

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

Related methods:

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:

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.

Constant Value Description
marquee_forever ffffffff Indicates that marquee should repeat indefinitely.

Related methods:

android:maxEms

Makes the TextView be at most this many ems wide.

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

Related methods:

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:

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:

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:

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:

android:minEms

Makes the TextView be at least this many ems wide.

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

Related methods:

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:

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:

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:

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.

Constant Value Description
decimal 5 Input is numeric, with decimals allowed.
integer 1 Input is numeric.
signed 3 Input is numeric, with sign allowed.

Related methods:

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:

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:

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:

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:

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:

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:

android:shadowDx

Horizontal offset of the text shadow.

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

Related methods:

android:shadowDy

Vertical offset of the text shadow.

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

Related methods:

android:shadowRadius

Blur radius of the text shadow.

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

Related methods:

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:

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:

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:

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:

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:

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:

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:

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:

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:

android:textScaleX

Sets the horizontal scaling factor for the text.

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

Related methods:

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:

android:textStyle

Style (normal, bold, italic, bold|italic) for the text.

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

Constant Value Description
bold 1  
italic 2  
normal 0  

Related methods:

android:typeface

Typeface (normal, sans, serif, monospace) for the text.

Must be one of the following constant values.

Constant Value Description
monospace 3  
normal 0  
sans 1  
serif 2  

Related methods:

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:

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

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

Prints information about this view in the log output, with the tag VIEW_LOG_TAG. Each line in the output is preceded with an indentation defined by the depth.

Parameters
depth int: the indentation level

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.

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 andFIND_VIEWS_WITH_CONTENT_DESCRIPTION flags.

Parameters
outViews ArrayList: The output list of matching Views.
searched CharSequence: The text to match against.
flags int

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:

Returns
int

getAutoSizeMaxTextSize

added in API level 26

 

public int getAutoSizeMaxTextSize ()

Related XML Attributes:

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:

getAutoSizeMinTextSize

added in API level 26

 

public int getAutoSizeMinTextSize ()

Related XML Attributes:

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:

getAutoSizeStepGranularity

added in API level 26

 

public int getAutoSizeStepGranularity ()

Related XML Attributes:

Returns
int the current auto-size step granularity in pixels.

See also:

getAutoSizeTextAvailableSizes

added in API level 26

 

public int[] getAutoSizeTextAvailableSizes ()

Returns
int[] the current auto-size int sizes array (in pixels).

See also:

getAutoSizeTextType

added in API level 26

 

public int getAutoSizeTextType ()

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

Related XML Attributes:

Returns
int an int corresponding to one of the auto-size types: AUTO_SIZE_TEXT_TYPE_NONE orAUTO_SIZE_TEXT_TYPE_UNIFORM

Value is AUTO_SIZE_TEXT_TYPE_NONE or AUTO_SIZE_TEXT_TYPE_UNIFORM.

See also:

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 either AUTOFILL_TYPE_NONEAUTOFILL_TYPE_TEXTAUTOFILL_TYPE_LISTAUTOFILL_TYPE_DATE, or AUTOFILL_TYPE_TOGGLE.

Value is AUTOFILL_TYPE_NONEAUTOFILL_TYPE_TEXTAUTOFILL_TYPE_TOGGLEAUTOFILL_TYPE_LIST or 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:

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:

Returns
int the current strategy for breaking paragraphs into lines.

Value is BREAK_STRATEGY_SIMPLEBREAK_STRATEGY_HIGH_QUALITY or BREAK_STRATEGY_BALANCED.

See also:

getCompoundDrawablePadding

added in API level 1

 

public int getCompoundDrawablePadding ()

Returns the padding between the compound drawables and the text.

Related XML Attributes:

Returns
int

getCompoundDrawableTintList

added in API level 23

 

public ColorStateList getCompoundDrawableTintList ()

Related XML Attributes:

Returns
ColorStateList the tint applied to the compound drawables

See also:

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:

Returns
PorterDuff.Mode the blending mode used to apply the tint to the compound drawables

See also:

getCompoundDrawables

added in API level 1

 

public Drawable[] getCompoundDrawables ()

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

Related XML Attributes:

Returns
Drawable[]

This value will never be null.

getCompoundDrawablesRelative

added in API level 17

 

public Drawable[] getCompoundDrawablesRelative ()

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

Related XML Attributes:

Returns
Drawable[]

This value will never 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:

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:

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:

Returns
int

See also:

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:

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:

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:

getGravity

added in API level 1

 

public int getGravity ()

Returns the horizontal and vertical alignment of this TextView.

Related XML Attributes:

Returns
int

See also:

getHighlightColor

added in API level 16

 

public int getHighlightColor ()

Related XML Attributes:

Returns
int the color used to display the selection highlight

See also:

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:

Returns
CharSequence

getHintTextColors

added in API level 1

 

public final ColorStateList getHintTextColors ()

Related XML Attributes:

Returns
ColorStateList the color of the hint text, for the different states of this TextView.

See also:

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:

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

Value is HYPHENATION_FREQUENCY_NORMALHYPHENATION_FREQUENCY_FULL or HYPHENATION_FREQUENCY_NONE.

See also:

getImeActionId

added in API level 3

 

public int getImeActionId ()

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

Returns
int

See also:

getImeActionLabel

added in API level 3

 

public CharSequence getImeActionLabel ()

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

Returns
CharSequence

See also:

getImeHintLocales

added in API level 24

 

public LocaleList getImeHintLocales ()

Returns
LocaleList The current languages list "hint". null when no "hint" is available.

See also:

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:

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:

Returns
boolean

See also:

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:

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:

getInputType

added in API level 3

 

public int getInputType ()

Get the type of the editable content.

Returns
int

See also:

getJustificationMode

added in API level 26

 

public int getJustificationMode ()

Returns
int true if currently paragraph justification mode.

Value is JUSTIFICATION_MODE_NONE or JUSTIFICATION_MODE_INTER_WORD.

See also:

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:

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:

Returns
int

See also:

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:

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

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:

Returns
float the extra space that is added to the height of each lines of this TextView.

See also:

getLineSpacingMultiplier

added in API level 16

 

public float getLineSpacingMultiplier ()

Gets the line spacing multiplier

Related XML Attributes:

Returns
float the value by which each line's height is multiplied to get its actual height.

See also:

getLinkTextColors

added in API level 1

 

public final ColorStateList getLinkTextColors ()

Related XML Attributes:

Returns
ColorStateList the list of colors used to paint the links in the text, for the different states of this TextView

See also:

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:

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:

Returns
int the number of times the marquee animation is repeated. -1 if the animation repeats indefinitely

See also:

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:

Returns
int the maximum width of TextView in terms of ems or -1 if the maximum width is not defined in ems

See also:

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:

Returns
int the maximum height of TextView in terms of pixels or -1 if the maximum height is not defined in pixels

See also:

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:

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:

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:

Returns
int the maximum width of TextView in terms of pixels. -1 if the maximum width is not defined in pixels

See also:

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:

Returns
int the minimum width of TextView in terms of ems. -1 if the minimum width is not defined in ems

See also:

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:

Returns
int the minimum height of TextView in terms of pixels or -1 if the minimum height is not defined in pixels

See also:

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:

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:

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:

Returns
int the minimum width of TextView in terms of pixels or -1 if the minimum width is not defined in pixels

See also:

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:

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:

getPrivateImeOptions

added in API level 3

 

public String getPrivateImeOptions ()

Get the private type of the content.

Returns
String

See also:

getSelectionEnd

added in API level 1

 

public int getSelectionEnd ()

Convenience for Selection.getSelectionEnd(CharSequence).

Returns
int

getSelectionStart

added in API level 1

 

public int getSelectionStart ()

Convenience for Selection.getSelectionStart(CharSequence).

Returns
int

getShadowColor

added in API level 16

 

public int getShadowColor ()

Gets the color of the shadow layer.

Related XML Attributes:

Returns
int the color of the shadow layer

See also:

getShadowDx

added in API level 16

 

public float getShadowDx ()

Related XML Attributes:

Returns
float the horizontal offset of the shadow layer

See also:

getShadowDy

added in API level 16

 

public float getShadowDy ()

Gets the vertical offset of the shadow layer.

Related XML Attributes:

Returns
float The vertical offset of the shadow layer.

See also:

getShadowRadius

added in API level 16

 

public float getShadowRadius ()

Gets the radius of the shadow layer.

Related XML Attributes:

Returns
float the radius of the shadow layer. If 0, the shadow layer is not visible

See also:

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

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 will never 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:

Returns
ColorStateList

See also:

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 will never 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 will never 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 will never be null.

See also:

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.

getTextSize

added in API level 1

 

public float getTextSize ()

Returns
float the size (in pixels) of the default text size in this TextView.

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:

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:

Returns
Typeface The current Typeface.

See also:

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(Object) and Spanned.getSpanEnd(Object) 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 inside this text view.

Returns
boolean

invalidateDrawable

added in API level 1

 

public void invalidateDrawable (Drawable drawable)

Invalidates the specified Drawable.

Parameters
drawable Drawable: the drawable to invalidate

This value must never 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:

isCursorVisible

added in API level 16

 

public boolean isCursorVisible ()

Related XML Attributes:

Returns
boolean whether or not the cursor is visible (assuming this TextView is editable)

See also:

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:

isFallbackLineSpacing

added in API level 28

 

public boolean isFallbackLineSpacing ()

Related XML Attributes:

Returns
boolean whether fallback line spacing is enabled, true by default

See also:

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.

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_SUBJECTInputType.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:

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.

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(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(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 callingInputConnection.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

onDragEvent

added in API level 11

 

public boolean onDragEvent (DragEvent event)

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

When the system calls this method, it passes a DragEvent object. A call to DragEvent.getAction() returns one of the action type constants defined in DragEvent. The method uses these to determine what is happening in the drag and drop operation.

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 true if the method was successful, otherwise false.

The method should return true in response to an action type ofDragEvent.ACTION_DRAG_STARTED to receive drag events for the current operation.

The method should also return true in response to an action type of DragEvent.ACTION_DROP if it consumed the drop, or false if it didn't.

For all other events, the return value is ignored.

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_NEXTEditorInfo.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:

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_CENTERKeyEvent.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 callingInputConnection.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.

onProvideAutofillStructure

added in API level 26

 

public void onProvideAutofillStructure (ViewStructure structure, int flags)

Populates a ViewStructure to fullfil an autofill request.

The structure should contain at least the following properties:

It's also recommended to set the following properties - the more properties the structure has, the higher the changes of an AutofillService properly using the structure:

The default implementation of this method already sets most of these properties based on related View methods (for example, the autofill id is set using getAutofillId(), the autofill type set using getAutofillType(), etc.), and views in the standard Android widgets library also override it to set their relevant properties (for example, TextView already sets the text properties), so it's recommended to only override this method (and call super.onProvideAutofillStructure()) when:

Note: The left and top values set in ViewStructure.setDimens(int, int, int, int, int, int) must be relative to the next isImportantForAutofill() predecessor view included in the structure.

Views support the Autofill Framework mainly by:

  • Providing the metadata defining what the view means and how it can be autofilled.
  • Notifying the Android System when the view value changed by callingAutofillManager.notifyValueChanged(View).
  • Implementing the methods that autofill the view.

This method is responsible for the former; autofill(AutofillValue) is responsible for the latter.

Parameters
structure ViewStructure: fill in with structured view data for autofill purposes.
flags int: optional flags.

onProvideStructure

added in API level 23

 

public void onProvideStructure (ViewStructure structure)

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

Parameters
structure ViewStructure: Fill in with structured view data. The default implementation fills in all data that can be inferred from the view itself.

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.

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

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.

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.selectAllR.id.cutR.id.copyR.id.paste 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.

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 View.AccessibilityDelegate has been specified via callingsetAccessibilityDelegate(AccessibilityDelegate) itsView.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:

Parameters
allCaps boolean

See also:

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.

Related XML Attributes:

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:

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:

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:

Parameters
presetSizes int: an int array of sizes in pixels

This value must never 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

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:

Parameters
autoSizeTextType int: the type of auto-size. Must be one of AUTO_SIZE_TEXT_TYPE_NONE orAUTO_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:

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.

Related XML Attributes:

Parameters
breakStrategy int

Value is BREAK_STRATEGY_SIMPLEBREAK_STRATEGY_HIGH_QUALITY or BREAK_STRATEGY_BALANCED.

See also:

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:

Parameters
pad int

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 PorterDuff.Mode.SRC_INby default.

Subsequent calls to setCompoundDrawables(Drawable, Drawable, Drawable, Drawable) and related methods will automatically mutate the drawables and apply the specified tint and tint mode usingDrawable.setTintList(ColorStateList).

Related XML Attributes:

Parameters
tint ColorStateList: the tint to apply, may be null to clear tint

See also:

setCompoundDrawableTintMode

added in API level 23

 

public void setCompoundDrawableTintMode (PorterDuff.Mode tintMode)

Specifies the blending mode used to apply the tint specified by setCompoundDrawableTintList(ColorStateList) to the compound drawables. The default mode is PorterDuff.Mode.SRC_IN.

Related XML Attributes:

Parameters
tintMode PorterDuff.Mode: the blending mode used to apply the tint, may be null to clear tint

See also:

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(Rect) called.

Calling this method will overwrite any Drawables previously set using setCompoundDrawablesRelative(Drawable, Drawable, Drawable, Drawable) or related methods.

Related XML Attributes:

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(Rect) called.

Calling this method will overwrite any Drawables previously set using setCompoundDrawables(Drawable, Drawable, Drawable, Drawable) or related methods.

Related XML Attributes:

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:

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:

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:

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:

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.

Related XML Attributes:

Parameters
visible boolean

See also:

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 itsActionMode.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 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 ofActionMode.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 itsActionMode.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.selectAllR.id.cutR.id.copyR.id.pasteR.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 ofActionMode.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.FactoryEditable.Factory to be used

See also:

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:

Parameters
elegant boolean: set the paint's elegant metrics flag.

See also:

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:

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 assetMinEms(int) or setMaxEms(int).

Related XML Attributes:

Parameters
ems int: the exact width of the TextView in terms of ems

See also:

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(Rect) 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(ExtractedTextRequest, 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:

Parameters
enabled boolean: whether to expand linespacing based on fallback fonts, true by default

See also:

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:

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 equal to the distance between the firt text baseline and the top of this TextView. Note that if FontMetrics.top or FontMetrics.ascent was already greater than firstBaselineToTopHeight, the top padding is not updated.

Related XML Attributes:

Parameters
firstBaselineToTopHeight int: distance between first baseline to top of the container in pixels

See also:

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:

Parameters
fontFeatureSettings String: font feature settings represented as CSS compatible string

This value may be null.

See also:

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");
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:

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:

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:

Parameters
gravity int

See also:

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:

Parameters
pixels int: the exact height of the TextView in terms of pixels

See also:

setHighlightColor

added in API level 1

 

public void setHighlightColor (int color)

Sets the color used to display the selection highlight.

Related XML Attributes:

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:

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:

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:

Parameters
colors ColorStateList

See also:

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:

Parameters
color int

See also:

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:

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_NORMAL. Note that the default hyphenation frequency value is set from the theme.

Related XML Attributes:

Parameters
hyphenationFrequency int: The hyphenation frequency to use.

Value is HYPHENATION_FREQUENCY_NORMALHYPHENATION_FREQUENCY_FULL or HYPHENATION_FREQUENCY_NONE.

See also:

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:

Parameters
label CharSequence
actionId int

See also:

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.hintLocaleswhen 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:

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:

Parameters
imeOptions int

See also:

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:

Parameters
includepad boolean

See also:

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:

Parameters
xmlResId int
Throws
XmlPullParserException  
IOException  

See also:

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(KeyListener), to match the given content type. If the given content type is InputType.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 InputType.TYPE_TEXT_FLAG_MULTI_LINEflag of the input type.

Related XML Attributes:

Parameters
type int

See also:

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 JUSTIFICATION_MODE_NONE or JUSTIFICATION_MODE_INTER_WORD.

See also:

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:

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 equal to the distance between the last text baseline and the bottom of this TextView. Note that if FontMetrics.bottom or FontMetrics.descentwas already greater than lastBaselineToBottomHeight, the bottom padding is not updated.

Related XML Attributes:

Parameters
lastBaselineToBottomHeight int: distance between last baseline to bottom of the container in pixels

See also:

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:

Parameters
letterSpacing float: A text letter-space value in ems.

See also:

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:

Parameters
lineHeight int: the line height in pixels

See also:

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:

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:

Parameters
lines int: the exact height of the TextView in terms of lines

See also:

setLinkTextColor

added in API level 1

 

public final void setLinkTextColor (ColorStateList colors)

Sets the color of links in the text.

Related XML Attributes:

Parameters
colors ColorStateList

See also:

setLinkTextColor

added in API level 1

 

public final void setLinkTextColor (int color)

Sets the color of links in the text.

Related XML Attributes:

Parameters
color int

See also:

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:

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:

Parameters
marqueeLimit int

See also:

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:

Parameters
maxEms int: the maximum width of TextView in terms of ems

See also:

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:

Parameters
maxPixels int: the maximum height of TextView in terms of pixels

See also:

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:

Parameters
maxLines int: the maximum height of TextView in terms of number of lines

See also:

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:

Parameters
maxPixels int: the maximum width of TextView in terms of pixels

See also:

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:

Parameters
minEms int: the minimum width of TextView in terms of ems

See also:

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:

Parameters
minPixels int: the minimum height of TextView in terms of pixels

See also:

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:

Parameters
minLines int: the minimum height of TextView in terms of number of lines

See also:

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:

Parameters
minPixels int: the minimum width of TextView in terms of pixels

See also:

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:

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:

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:

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:

Parameters
type String

See also:

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:

Parameters
type int

See also:

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:

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:

Parameters
radius float
dx float
dy float
color int

See also:

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.

Related XML Attributes:

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:

setSpannableFactory

added in API level 1

 

public final void setSpannableFactory (Spannable.Factory factory)

Sets the Factory used to create new Spannables.

Parameters
factory Spannable.FactorySpannable.Factory to be used

See also:

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:

Parameters
resid int: the resource identifier of the string resource to be displayed

See also:

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 useEditable.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 setTextMetricsParams(PrecomputedText.Params) before calling this.

Related XML Attributes:

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 useEditable.Factory to create final or intermediate Editables.

Related XML Attributes:

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

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 useEditable.Factory to create final or intermediate Editables.

Related XML Attributes:

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

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

 

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:

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:

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

added in API level 1

 

public void setTextColor (ColorStateList colors)

Sets the text color.

Related XML Attributes:

Parameters
colors ColorStateList

See also:

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 attributeR.styleable.TextView_textIsSelectable to "true".

When you call this method to set the value of textIsSelectable, it sets the flags focusablefocusableInTouchModeclickable, and longClickable to the same value. These flags correspond to the attributesandroid:focusableandroid:focusableInTouchModeandroid: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(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 useEditable.Factory to create final or intermediate Editables.

Parameters
text CharSequence: text to be displayed

See also:

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 assetText(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 useEditable.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:

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

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:

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 must never be null.

See also:

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:

Parameters
size float: The horizontal scale factor.

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 than this function is no-op.

Related XML Attributes:

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 than this function is no-op.

Related XML Attributes:

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:

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(Typeface, int) to get the appearance that you actually want.

Related XML Attributes:

Parameters
tf Typeface

This value may be null.

See also:

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:

Parameters
tf Typeface

This value may be null.

style int

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:

Parameters
pixels int: the exact width of the TextView in terms of pixels

See also:

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.

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

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.

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_UPView.FOCUS_DOWNView.FOCUS_LEFTView.FOCUS_RIGHTView.FOCUS_FORWARD, or View.FOCUS_BACKWARD. It may not always apply, in which case use the default.
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 withView.MeasureSpec.
heightMeasureSpec int: vertical space requirements as imposed by the parent. The requirements are encoded withView.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.

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.
visibility int: The new visibility, one of View.VISIBLEView.INVISIBLE or View.GONE.

setFrame

added in API level 1

 

protected boolean setFrame (int l, int t, int r, int b)

Assign a size and position to this view. This is called from layout.

Parameters
l int: Left position, relative to parent
t int: Top position, relative to parent
r int: Right position, relative to parent
b int: Bottom position, relative to parent
Returns
boolean true if the new size and position are different than the previous ones

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.

Parameters
who Drawable: The Drawable to verify. Return true if it is one you are displaying, else return the result of calling through to the super class.

This value must never be null.

Returns
boolean boolean If true than the Drawable is being displayed in the view; else false and it is not allowed to animate.

猜你喜欢

转载自blog.csdn.net/u011038298/article/details/84838487