Class TextView

java.lang.Object
icyllis.modernui.view.View
icyllis.modernui.widget.TextView
All Implemented Interfaces:
Drawable.Callback, ViewTreeObserver.OnPreDrawListener
Direct Known Subclasses:
Button, EditText

public class TextView extends View implements ViewTreeObserver.OnPreDrawListener
A user interface element that displays text to the user. To provide user-editable text, see EditText.

To display a styled text, use a Spannable with markup objects, like CharacterStyle. TextView will hold a copy of your text after calling setText(CharSequence, BufferType). After you provide a String, you want it to have styles:

  TextView textView = new TextView();
  textView.setText(string, TextView.BufferType.SPANNABLE);
  // add styles
  Spannable spannable = (Spannable) textView.getText();
  spannable.setSpan(new ForegroundColorSpan(0xfff699b4), 0, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
 
If you want a non-editable text to be selected, see setTextIsSelectable(boolean).

Explore the methods in this class to find more usage

  • Field Details

  • Constructor Details

    • TextView

      public TextView(Context context)
  • Method Details

    • getMovementMethod

      @Nullable 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-editable TextViews.
      Returns:
      the movement method being used for this TextView.
      See Also:
    • setMovementMethod

      public final void setMovementMethod(@Nullable 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 movement method not to be focusable, or if you want a TextView without a 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 - the movement method to set
    • getTransformationMethod

      @Nullable public final TransformationMethod getTransformationMethod()
      Gets the current TransformationMethod for the TextView. This is frequently null, except for single-line and password fields.
      Returns:
      the current transformation method for this TextView.
    • setTransformationMethod

      public final void setTransformationMethod(@Nullable TransformationMethod method)
      Sets the transformation that is applied to the text that this TextView is displaying.
      Parameters:
      method - the transformation method to set
    • getCompoundPaddingTop

      public int getCompoundPaddingTop()
      Returns the top padding of the view, plus space for the top Drawable if any.
    • getCompoundPaddingBottom

      public int getCompoundPaddingBottom()
      Returns the bottom padding of the view, plus space for the bottom Drawable if any.
    • getCompoundPaddingLeft

      public int getCompoundPaddingLeft()
      Returns the left padding of the view, plus space for the left Drawable if any.
    • getCompoundPaddingRight

      public int getCompoundPaddingRight()
      Returns the right padding of the view, plus space for the right Drawable if any.
    • getCompoundPaddingStart

      public int getCompoundPaddingStart()
      Returns the start padding of the view, plus space for the start Drawable if any.
    • getCompoundPaddingEnd

      public int getCompoundPaddingEnd()
      Returns the end padding of the view, plus space for the end Drawable if any.
    • getExtendedPaddingTop

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

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

      public int getTotalPaddingLeft()
      Returns the total left padding of the view, including the left Drawable if any.
    • getTotalPaddingRight

      public int getTotalPaddingRight()
      Returns the total right padding of the view, including the right Drawable if any.
    • getTotalPaddingStart

      public int getTotalPaddingStart()
      Returns the total start padding of the view, including the start Drawable if any.
    • getTotalPaddingEnd

      public int getTotalPaddingEnd()
      Returns the total end padding of the view, including the end Drawable if any.
    • getTotalPaddingTop

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

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

      public void setCompoundDrawables(@Nullable Drawable left, @Nullable Drawable top, @Nullable Drawable right, @Nullable 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(int, int, int, int) called.

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

    • setCompoundDrawablesWithIntrinsicBounds

      public void setCompoundDrawablesWithIntrinsicBounds(@Nullable Drawable left, @Nullable Drawable top, @Nullable Drawable right, @Nullable 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(icyllis.modernui.graphics.drawable.Drawable, icyllis.modernui.graphics.drawable.Drawable, icyllis.modernui.graphics.drawable.Drawable, icyllis.modernui.graphics.drawable.Drawable) or related methods.

    • setCompoundDrawablesRelative

      public void setCompoundDrawablesRelative(@Nullable Drawable start, @Nullable Drawable top, @Nullable Drawable end, @Nullable 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(int, int, int, int) called.

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

    • setCompoundDrawablesRelativeWithIntrinsicBounds

      public void setCompoundDrawablesRelativeWithIntrinsicBounds(@Nullable Drawable start, @Nullable Drawable top, @Nullable Drawable end, @Nullable 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(icyllis.modernui.graphics.drawable.Drawable, icyllis.modernui.graphics.drawable.Drawable, icyllis.modernui.graphics.drawable.Drawable, icyllis.modernui.graphics.drawable.Drawable) or related methods.

    • getCompoundDrawables

      @NonNull public Drawable[] getCompoundDrawables()
      Returns drawables for the left, top, right, and bottom borders.
    • getCompoundDrawablesRelative

      @NonNull public Drawable[] getCompoundDrawablesRelative()
      Returns drawables for the start, top, end, and bottom borders.
    • setCompoundDrawablePadding

      public void setCompoundDrawablePadding(int pad)
      Sets the size of the padding between the compound drawables and the text.
    • getCompoundDrawablePadding

      public int getCompoundDrawablePadding()
      Returns the padding between the compound drawables and the text.
    • setPadding

      public void setPadding(int left, int top, int right, int bottom)
      Description copied from class: View
      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 View.getPaddingLeft(), View.getPaddingTop(), View.getPaddingRight() and View.getPaddingBottom() may be different from the values set in this call.
      Overrides:
      setPadding in class View
      Parameters:
      left - the left padding in pixels
      top - the top padding in pixels
      right - the right padding in pixels
      bottom - the bottom padding in pixels
    • setPaddingRelative

      public void setPaddingRelative(int start, int top, int end, int bottom)
      Description copied from class: View
      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 View.getPaddingStart(), View.getPaddingTop(), View.getPaddingEnd() and View.getPaddingBottom() may be different from the values set in this call.
      Overrides:
      setPaddingRelative in class View
      Parameters:
      start - the start padding in pixels
      top - the top padding in pixels
      end - the end padding in pixels
      bottom - the bottom padding in pixels
    • setFirstBaselineToTopHeight

      public void setFirstBaselineToTopHeight(int firstBaselineToTopHeight)
      Updates the top padding of the TextView so that firstBaselineToTopHeight is the distance between the top of the TextView and first line's baseline. Note that if FontMetrics.top or FontMetrics.ascent was already greater than firstBaselineToTopHeight, the top padding is not updated. Moreover, since this function sets the top padding, if the height of the TextView is less than the sum of top padding, line height and bottom padding, top of the line will be pushed down and bottom will be clipped.
      Parameters:
      firstBaselineToTopHeight - distance between first baseline to top of the container in pixels
      See Also:
    • setLastBaselineToBottomHeight

      public void setLastBaselineToBottomHeight(int lastBaselineToBottomHeight)
      Updates the bottom padding of the TextView so that lastBaselineToBottomHeight is the distance between the bottom of the TextView and the last line's baseline. Note that if FontMetrics.bottom or FontMetrics.descent was already greater than lastBaselineToBottomHeight, the bottom padding is not updated. Moreover, since this function sets the bottom padding, if the height of the TextView is less than the sum of top padding, line height and bottom padding, bottom of the text will be clipped.
      Parameters:
      lastBaselineToBottomHeight - distance between last baseline to bottom of the container in pixels
      See Also:
    • getFirstBaselineToTopHeight

      public int getFirstBaselineToTopHeight()
      Returns the distance between the first text baseline and the top of this TextView.
      See Also:
    • getLastBaselineToBottomHeight

      public int getLastBaselineToBottomHeight()
      Returns the distance between the last text baseline and the bottom of this TextView.
      See Also:
    • getTextLocale

      @NonNull public Locale getTextLocale()
      Get the default primary Locale of the text in this TextView.
      Returns:
      the default primary Locale of the text in this TextView.
    • setTextLocale

      public void setTextLocale(@NonNull Locale locale)
      Set the default Locale of the text in this TextView to the given Locale.
      Parameters:
      locale - the Locale for drawing text, must not be null.
    • getTextSize

      public float getTextSize()
      Returns:
      the size (in pixels) of the default text size in this TextView.
    • setTextSize

      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.
      Parameters:
      size - The scaled pixel size.
    • setTextSize

      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.
      Parameters:
      unit - The desired dimension unit.
      size - The desired size in the given units.
    • setTextStyle

      public void setTextStyle(int style)
      Sets the default text style in which the text should be displayed.
      Parameters:
      style - the text style to set
      See Also:
    • getTextStyle

      public int getTextStyle()
      Gets the current text style that is used to style the text.
      Returns:
      the current text style
      See Also:
    • setTypeface

      public void setTypeface(@NonNull Typeface tf)
      Sets the typeface in which the text should be displayed.
      See Also:
    • getTypeface

      @NonNull public Typeface getTypeface()
      Gets the current Typeface that is used to style the text.
      Returns:
      The current Typeface.
      See Also:
    • getLineHeight

      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:
      The height of one standard line in pixels.
    • setFallbackLineSpacing

      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.

      Parameters:
      enabled - whether to expand line spacing based on fallback fonts, true by default
      See Also:
    • isFallbackLineSpacing

      public boolean isFallbackLineSpacing()
      Returns:
      whether fallback line spacing is enabled, true by default
      See Also:
    • setLineBreakStyle

      public void setLineBreakStyle(int lineBreakStyle)
      Set the line break style for text wrapping.

      The line break style to indicates the line break strategies can be used when calculating the text wrapping. The line break style affects rule-based breaking. It specifies the strictness of line-breaking rules. There are several types for the line break style: LineBreakConfig.LINE_BREAK_STYLE_LOOSE, LineBreakConfig.LINE_BREAK_STYLE_NORMAL and LineBreakConfig.LINE_BREAK_STYLE_STRICT. The default values of the line break style is LineBreakConfig.LINE_BREAK_STYLE_NONE, indicating no breaking rule is specified. See the line-break property

      Parameters:
      lineBreakStyle - the line break style for the text.
    • setLineBreakWordStyle

      public void setLineBreakWordStyle(int lineBreakWordStyle)
      Set the line break word style for text wrapping.

      The line break word style affects dictionary-based breaking and provide phrase-based breaking opportunities. The type for the line break word style is LineBreakConfig.LINE_BREAK_WORD_STYLE_PHRASE. The default values of the line break word style is LineBreakConfig.LINE_BREAK_WORD_STYLE_NONE, indicating no breaking rule is specified. See the word-break property

      Parameters:
      lineBreakWordStyle - the line break word style for the tet
    • getLineBreakStyle

      public int getLineBreakStyle()
      Get the current line break style for text wrapping.
      Returns:
      the current line break style to be used for text wrapping.
    • getLineBreakWordStyle

      public int getLineBreakWordStyle()
      Get the current line word break style for text wrapping.
      Returns:
      the current line break word style to be used for text wrapping.
    • getTextMetricsParams

      @NonNull public PrecomputedText.Params getTextMetricsParams()
      Gets the parameters for text layout pre-computation, for use with PrecomputedText.
      Returns:
      a current PrecomputedText.Params
      See Also:
    • setTextMetricsParams

      public void setTextMetricsParams(@NonNull PrecomputedText.Params params)
      Apply the text layout parameter.

      Update the TextView parameters to be compatible with PrecomputedText.Params.

      See Also:
    • setTextColor

      public void setTextColor(int color)
      Sets the text color for all the states (normal, selected, focused) to be this color.
      Parameters:
      color - A color value in the form 0xAARRGGBB.
      See Also:
    • setTextColor

      public void setTextColor(ColorStateList colors)
      Sets the text color.
      See Also:
    • getTextColors

      public final ColorStateList getTextColors()
      Gets the text colors for the different states (normal, selected, focused) of the TextView.
      See Also:
    • getCurrentTextColor

      public final int getCurrentTextColor()
      Return the current color selected for normal text.
      Returns:
      Returns the current text color.
    • setHighlightColor

      public void setHighlightColor(int color)
      Sets the color used to display the selection highlight.
    • getHighlightColor

      public int getHighlightColor()
      Returns:
      the color used to display the selection highlight
      See Also:
    • getPaint

      @NonNull 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:
      The base paint used for the text.
    • getLayout

      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:
      The Layout that is currently being used to display the text.
    • setAutoLinkMask

      public final void setAutoLinkMask(int mask)
      Sets the autolink mask of the text.
    • getAutoLinkMask

      public final int getAutoLinkMask()
      Gets the autolink mask of the text.
    • setLinksClickable

      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(java.lang.CharSequence). The default is true.
    • getLinksClickable

      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(java.lang.CharSequence). The default is true.
    • setHintTextColor

      public final void setHintTextColor(int color)
      Sets the color of the hint text for all the states (disabled, focussed, selected...) of this TextView.
      See Also:
    • setHintTextColor

      public final void setHintTextColor(ColorStateList colors)
      Sets the color of the hint text.
      See Also:
    • getHintTextColors

      public final ColorStateList getHintTextColors()
      Returns:
      the color of the hint text, for the different states of this TextView.
      See Also:
    • getCurrentHintTextColor

      public final int getCurrentHintTextColor()

      Return the current color selected to paint the hint text.

      Returns:
      Returns the current hint text color.
    • setLinkTextColor

      public final void setLinkTextColor(int color)
      Sets the color of links in the text.
      See Also:
    • setLinkTextColor

      public final void setLinkTextColor(ColorStateList colors)
      Sets the color of links in the text.
      See Also:
    • getLinkTextColors

      public final ColorStateList getLinkTextColors()
      Returns:
      the list of colors used to paint the links in the text, for the different states of this TextView
      See Also:
    • setGravity

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

      public int getGravity()
      Returns the horizontal and vertical alignment of this TextView.
      See Also:
    • setHorizontallyScrolling

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

      public final boolean isHorizontallyScrollable()
      Returns whether the text is allowed to be wider than the View. If false, the text will be wrapped to the width of the View.
      See Also:
    • setMinLines

      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.

      Parameters:
      minLines - the minimum height of TextView in terms of number of lines
      See Also:
    • getMinLines

      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).
      Returns:
      the minimum height of TextView in terms of number of lines or -1 if the minimum height is not defined in lines
      See Also:
    • setMinHeight

      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.

      Parameters:
      minPixels - the minimum height of TextView in terms of pixels
      See Also:
    • getMinHeight

      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).
      Returns:
      the minimum height of TextView in terms of pixels or -1 if the minimum height is not defined in pixels
      See Also:
    • setMaxLines

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

      Parameters:
      maxLines - the maximum height of TextView in terms of number of lines
      See Also:
    • getMaxLines

      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).
      Returns:
      the maximum height of TextView in terms of number of lines. -1 if the maximum height is not defined in lines.
      See Also:
    • setMaxHeight

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

      Parameters:
      maxPixels - the maximum height of TextView in terms of pixels
      See Also:
    • getMaxHeight

      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).
      Returns:
      the maximum height of TextView in terms of pixels or -1 if the maximum height is not defined in pixels
      See Also:
    • setLines

      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.

      Parameters:
      lines - the exact height of the TextView in terms of lines
      See Also:
    • setHeight

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

      Parameters:
      pixels - the exact height of the TextView in terms of pixels
      See Also:
    • setMinWidth

      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.

      The value given here is different from View.setMinimumWidth(int). Between minWidth and the value set in View.setMinimumWidth(int), the greater one is used to decide the final width.

      Parameters:
      minPixels - the minimum width of TextView in terms of pixels
      See Also:
    • getMinWidth

      public int getMinWidth()
      Returns the minimum width of TextView in terms of pixels.
      Returns:
      the minimum width of TextView in terms of pixels.
      See Also:
    • setMaxWidth

      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.

      Parameters:
      maxPixels - the maximum width of TextView in terms of pixels
      See Also:
    • getMaxWidth

      public int getMaxWidth()
      Returns the maximum width of TextView in terms of pixels.
      Returns:
      the maximum width of TextView in terms of pixels.
      See Also:
    • setWidth

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

      Parameters:
      pixels - the exact width of the TextView in terms of pixels
    • getText

      @NonNull 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.

      Returns:
      The text displayed by the text view.
    • getEditableText

      public Editable getEditableText()
      Return the text that TextView is displaying as an Editable object. If the text is not editable, null is returned.
      See Also:
    • setEditableFactory

      public final void setEditableFactory(@NonNull Editable.Factory factory)
      Sets the Factory used to create new Editables.
      Parameters:
      factory - Editable.Factory to be used
      See Also:
    • setSpannableFactory

      public final void setSpannableFactory(@NonNull Spannable.Factory factory)
      Sets the Factory used to create new Spannables.
      Parameters:
      factory - Spannable.Factory to be used
      See Also:
    • setText

      public final void setText(@NonNull CharSequence text)
      Sets the text to be displayed. To style your strings, attach CharacterStyle to a SpannableString.

      When required, TextView will use Spannable.Factory to create final or intermediate Spannables. Likewise, it will use Editable.Factory to create final or intermediate Editables.

      If the passed text is a PrecomputedText but the parameters used to create the PrecomputedText mismatches with this TextView, IllegalArgumentException is thrown.

      Parameters:
      text - 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.
    • setTextKeepState

      public final void setTextKeepState(@NonNull 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 use Editable.Factory to create final or intermediate Editables.

      Parameters:
      text - text to be displayed
      See Also:
    • setTextKeepState

      public final void setTextKeepState(@NonNull CharSequence text, @NonNull TextView.BufferType type)
      Sets the text to be displayed and the TextView.BufferType but retains the cursor position. Same as setText(CharSequence, BufferType) except that the cursor position (if any) is retained in the new text.

      When required, TextView will use Spannable.Factory to create final or intermediate Spannables. Likewise, it will use Editable.Factory to create final or intermediate Editables.

      Parameters:
      text - text to be displayed
      type - a TextView.BufferType which defines whether the text is stored as a static text, styleable/spannable text, or editable text
      See Also:
    • setText

      public void setText(@NonNull CharSequence text, @NonNull TextView.BufferType type)
      Sets the text to be displayed and the TextView.BufferType.

      When required, TextView will use Spannable.Factory to create final or intermediate Spannables. Likewise, it will use Editable.Factory to create final or intermediate Editables.

      Subclasses overriding this method should ensure that the following post condition holds, in order to guarantee the safety of the view's measurement and layout operations: regardless of the input, after calling #setText both mText and mTransformed will be different from null.

      Parameters:
      text - text to be displayed
      type - a TextView.BufferType which defines whether the text is stored as a static text, styleable/spannable text, or editable text
      See Also:
    • getHint

      @Nullable public CharSequence getHint()
      Returns the hint that is displayed when the text of the TextView is empty.
    • setHint

      public final void setHint(@Nullable 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.
    • setFilters

      public void setFilters(@NonNull InputFilter... filters)
      Sets the list of input filters that will be used if the buffer is Editable. Has no effect otherwise.
    • getFilters

      @NonNull public InputFilter[] getFilters()
      Returns the current list of input filters.
    • onPreDraw

      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.
      Specified by:
      onPreDraw in interface ViewTreeObserver.OnPreDrawListener
      Returns:
      Return true to proceed with the current drawing pass, or false to cancel.
      See Also:
    • onAttachedToWindow

      protected void onAttachedToWindow()
      Description copied from class: View
      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 View.onDraw(Canvas), however it may be called any time before the first onDraw -- including before or after View.onMeasure(int, int).
      Overrides:
      onAttachedToWindow in class View
      See Also:
    • onDetachedFromWindow

      protected void onDetachedFromWindow()
      Description copied from class: View
      This is called when the view is detached from a window. At this point it no longer has a surface for drawing.
      Overrides:
      onDetachedFromWindow in class View
      See Also:
    • verifyDrawable

      protected boolean verifyDrawable(@NonNull Drawable who)
      Description copied from class: View
      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.

      Overrides:
      verifyDrawable in class View
      Parameters:
      who - The Drawable to verify. Return true if it is one you are displaying, else return the result of calling through to the super class.
      Returns:
      boolean If true then the Drawable is being displayed in the view; else false and it is not allowed to animate.
      See Also:
    • jumpDrawablesToCurrentState

      public void jumpDrawablesToCurrentState()
      Description copied from class: View
      Call Drawable.jumpToCurrentState() on all Drawable objects associated with this view.

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

      Overrides:
      jumpDrawablesToCurrentState in class View
    • isTextSelectable

      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.

      Returns:
      True if the text displayed in this TextView can be selected by the user.
    • setTextIsSelectable

      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.

      When you call this method to set the value of textIsSelectable, it sets the flags focusable, focusableInTouchMode, clickable, and longClickable to the same value. 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().

      The content of an EditText (A editable TextView) can always be selected, and you should not the value of this flag.

      Parameters:
      selectable - Whether the content of this TextView should be selectable.
    • drawableStateChanged

      protected void drawableStateChanged()
      Description copied from class: View
      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.

      Overrides:
      drawableStateChanged in class View
      See Also:
    • onCreateDrawableState

      @NonNull protected int[] onCreateDrawableState(int extraSpace)
      Description copied from class: View
      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 View.getDrawableState().
      Overrides:
      onCreateDrawableState in class View
      Parameters:
      extraSpace - if non-zero, this is the number of extra entries you would like in the returned array in which you can place your own states.
      Returns:
      an array holding the current Drawable state of the view.
      See Also:
    • getHorizontalOffsetForDrawables

      public int getHorizontalOffsetForDrawables()
    • onDraw

      protected void onDraw(@NonNull Canvas canvas)
      Description copied from class: View
      Draw the content of this view, implement this to do your drawing.

      Note that (0, 0) will be the top left of the bounds, and (width, height) will be the bottom right of the bounds.

      Overrides:
      onDraw in class View
      Parameters:
      canvas - the canvas to draw content
    • getFocusedRect

      public void getFocusedRect(@NonNull Rect r)
      Description copied from class: View
      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 View.getDrawingRect(Rect)) of the view. However, if your view maintains some idea of internal selection, such as a cursor, or a selected row or column, you should override this method and fill in a more specific rectangle.

      Overrides:
      getFocusedRect in class View
      Parameters:
      r - The rectangle to fill in, in this view's coordinates.
    • getLineCount

      public int getLineCount()
      Return the number of lines of text, or 0 if the internal Layout has not been built.
    • getLineBounds

      public int getLineBounds(int line, @Nullable 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 - which line to examine (0..getLineCount() - 1)
      bounds - Optional. If not null, it returns the extent of the line
      Returns:
      the Y-coordinate of the baseline
    • getBaseline

      public int getBaseline()
      Description copied from class: View

      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.

      Overrides:
      getBaseline in class View
      Returns:
      the offset of the baseline within the widget's bounds or -1 if baseline alignment is not supported
    • nullLayouts

      @VisibleForTesting public final void nullLayouts()
    • makeNewLayout

      @VisibleForTesting public final void makeNewLayout(int wantWidth, int hintWidth, BoringLayout.Metrics boring, BoringLayout.Metrics hintBoring, int ellipsisWidth, boolean bringIntoView)
      The width passed in is now the desired layout width, not the full view width with padding.
    • useDynamicLayout

      @VisibleForTesting public final boolean useDynamicLayout()
      Returns true if DynamicLayout is required
    • setIncludeFontPadding

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

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

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

      CONTRACT: When overriding this method, you must call View.setMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger an IllegalStateException, thrown by View.measure(int, int). Calling super.onMeasure() is a valid use.

      The base class implementation of measure defaults to the background size, unless a larger size is allowed by the MeasureSpec. Subclasses should override the base one to provide better measurements of their content.

      Overrides:
      onMeasure in class View
      Parameters:
      widthMeasureSpec - width measure specification imposed by the parent MeasureSpec
      heightMeasureSpec - height measure specification imposed by the parent MeasureSpec
    • onLayout

      protected void onLayout(boolean changed, int left, int top, int right, int bottom)
      Description copied from class: View
      Called from View.layout(int, int, int, int) when this view should assign a size and position to each of its children.

      Derived classes with children should override this method and call layout on each of their children.

      Overrides:
      onLayout in class View
      Parameters:
      changed - This is a new size or position for this view
      left - Left position, relative to parent
      top - Top position, relative to parent
      right - Right position, relative to parent
      bottom - Bottom position, relative to parent
    • bringPointIntoView

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

      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:
      True if the cursor was actually moved, false otherwise.
    • getSelectionStart

      public int getSelectionStart()
    • getSelectionEnd

      public int getSelectionEnd()
    • hasSelection

      public boolean hasSelection()
      Return true iff there is a selection of nonzero length inside this text view.
    • setSingleLine

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

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

      Note that the default conditions are not necessarily those that were in effect prior this method, and you may want to reset these properties to your custom values.

      Note that due to performance reasons, by setting single line for the EditText, the maximum text length is set to 5000 if no other character limitation are applied.

    • setEllipsize

      public void setEllipsize(@Nullable 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 is supported (other ellipsizing types will not do anything).

    • getEllipsize

      @Nullable public TextUtils.TruncateAt getEllipsize()
      Returns where, if anywhere, words that are longer than the view is wide should be ellipsized.
    • setSelectAllOnFocus

      public void setSelectAllOnFocus(boolean selectAllOnFocus)
      Set the TextView so that when it takes focus, all the text is selected.
    • setCursorVisible

      public void setCursorVisible(boolean visible)
      Set whether the cursor is visible. The default is true. Note that this property only makes sense for editable TextView. If IME is consuming the input, the cursor will always be invisible, visibility will be updated as the last state when IME does not consume the input anymore.
      See Also:
    • isCursorVisible

      public boolean isCursorVisible()
      Returns:
      whether the cursor is visible (assuming this TextView is editable). This method may return false when the IME is consuming the input even if the mEditor.mCursorVisible attribute is true or #setCursorVisible(true) is called.
      See Also:
    • onTextChanged

      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 - The text the TextView is displaying
      start - The offset of the start of the range of the text that was modified
      lengthBefore - The length of the former text that has been replaced
      lengthAfter - The length of the replacement modified text
    • addTextChangedListener

      public void addTextChangedListener(@NonNull 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(icyllis.modernui.text.Editable) method was erroneously not called after setText(java.lang.CharSequence) calls. Now, doing setText(java.lang.CharSequence) 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 - the watcher to add
    • removeTextChangedListener

      public void removeTextChangedListener(@NonNull TextWatcher watcher)
      Removes the specified TextWatcher from the list of those whose methods are called whenever this TextView's text changes.
      Parameters:
      watcher - the watcher to remove
    • onFocusChanged

      protected void onFocusChanged(boolean focused, int direction, @Nullable Rect previouslyFocusedRect)
      Description copied from class: View
      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.
      Overrides:
      onFocusChanged in class View
      Parameters:
      focused - True if the View has focus; false otherwise.
      direction - The direction focus has moved when requestFocus() is called to give this view focus. Values are View.FOCUS_UP, View.FOCUS_DOWN, View.FOCUS_LEFT, View.FOCUS_RIGHT, View.FOCUS_FORWARD, or View.FOCUS_BACKWARD. It may not always apply, in which case use the default.
      previouslyFocusedRect - The rectangle, in this view's coordinate system, of the previously focused view. If applicable, this will be passed in as finer grained information about where the focus is coming from (in addition to direction). Will be null otherwise.
    • onTouchEvent

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

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

      Overrides:
      onTouchEvent in class View
      Parameters:
      event - the touch event
      Returns:
      true if the event was handled by the view, false otherwise
    • onGenericMotionEvent

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

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

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

      protected void onCreateContextMenu(@NonNull ContextMenu menu)
      Description copied from class: View
      Views should implement this if the view itself is going to add items to the context menu.
      Overrides:
      onCreateContextMenu in class View
      Parameters:
      menu - the context menu to populate
    • showContextMenu

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

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

      public void cancelLongPress()
      Description copied from class: View
      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.
      Overrides:
      cancelLongPress in class View
    • computeHorizontalScrollRange

      protected int computeHorizontalScrollRange()
      Description copied from class: View

      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 View.computeHorizontalScrollExtent() and View.computeHorizontalScrollOffset().

      The default range is the drawing width of this view.

      Overrides:
      computeHorizontalScrollRange in class View
      Returns:
      the total horizontal range represented by the horizontal scrollbar
      See Also:
    • computeVerticalScrollRange

      protected int computeVerticalScrollRange()
      Description copied from class: View

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

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

      The default range is the drawing height of this view.

      See Also:
    • computeVerticalScrollExtent

      protected int computeVerticalScrollExtent()
      Description copied from class: View

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

      The default extent is the drawing height of this view.

      Overrides:
      computeVerticalScrollExtent in class View
      Returns:
      the vertical extent of the scrollbar's thumb
      See Also:
    • onKeyDown

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

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

      public boolean onKeyShortcut(int keyCode, @NonNull KeyEvent event)
      Description copied from class: View
      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.
      Overrides:
      onKeyShortcut in class View
      Parameters:
      keyCode - The value in event.getKeyCode().
      event - Description of the key event.
      Returns:
      If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.
    • getWordIterator

      public WordIterator getWordIterator()
      This method is used by the ArrowKeyMovementMethod to jump from one word to the other. Made available to achieve a consistent behavior.
    • onTextContextMenuItem

      public boolean onTextContextMenuItem(int id)
      Called when a context menu option for the text view is selected. Currently, this will be one of R.id.selectAll, R.id.cut, R.id.copy, R.id.paste.
      Returns:
      true if the context menu item action was performed.
    • onRtlPropertiesChanged

      protected void onRtlPropertiesChanged(int layoutDirection)
      Description copied from class: View
      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.

      Overrides:
      onRtlPropertiesChanged in class View
      Parameters:
      layoutDirection - the direction of the layout
      See Also:
    • getTextDirectionHeuristic

      @NonNull public TextDirectionHeuristic getTextDirectionHeuristic()
      Returns resolved TextDirectionHeuristic that will be used for text layout. The TextDirectionHeuristic that is used by TextView is only available after View.getTextDirection() and View.getLayoutDirection() is resolved. Therefore the return value may not be the same as the one TextView uses if the View's layout direction is not resolved or detached from parent root view.
    • onResolveDrawables

      public void onResolveDrawables(int layoutDirection)
      Description copied from class: View
      Called when layout direction has been resolved.

      The default implementation does nothing.

      Overrides:
      onResolveDrawables in class View
      Parameters:
      layoutDirection - The resolved layout direction.
      See Also:
    • onResolvePointerIcon

      public PointerIcon onResolvePointerIcon(@NonNull MotionEvent event)
      Description copied from class: View
      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).
      Overrides:
      onResolvePointerIcon in class View
      Parameters:
      event - The MotionEvent from a mouse
      See Also:
    • setEnabled

      public void setEnabled(boolean enabled)
      Description copied from class: View
      Set the enabled state of this view. The interpretation of the enabled state varies by subclass.
      Overrides:
      setEnabled in class View
      Parameters:
      enabled - True if this view is enabled, false otherwise.
    • getOffsetForPosition

      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 - The horizontal absolute position of a point on screen
      y - The vertical absolute position of a point on screen
      Returns:
      the character offset for the character whose position is closest to the specified position. Returns -1 if there is no layout.