Android Studio
Added in API level 1

EditText


public class EditText
extends TextView

java.lang.Object
   ↳ android.view.View
     ↳ android.widget.TextView
       ↳ android.widget.EditText

AutoCompleteTextView

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

ExtractEditText * Specialization of EditText for showing and interacting with the extracted text in a full-screen input method. 


A user interface element for entering and modifying text. When you define an edit text widget, you must specify the R.styleable.TextView_inputType attribute. For example, for plain text input set inputType to "text":

 <EditText
     android:id="@+id/plain_text_input"
     android:layout_height="wrap_content"
     android:layout_width="match_parent"
     android:inputType="text"/>
Choosing the input type configures the keyboard type that is shown, acceptable characters, and appearance of the edit text. For example, if you want to accept a secret number, like a unique pin or serial number, you can set inputType to numberPassword. An input type of numberPassword results in an edit text that accepts numbers only, shows a numeric keyboard when focused, and masks the text that is entered for privacy.

See the Text Fields guide for examples of other R.styleable.TextView_inputType settings.

You also can receive callbacks as a user changes text by adding a TextWatcher to the edit text. This is useful when you want to add auto-save functionality as changes are made, or validate the format of user input, for example. You add a text watcher using the TextView.addTextChangedListener method.

This widget does not support auto-sizing text.

XML attributes

See EditText Attributes, TextView Attributes, View Attributes

Summary

XML attributes

android:enableTextStylingShortcuts Enables styling shortcuts, e.g. 

Inherited XML attributes

From class android.widget.TextView android:allowUndo Whether undo should be allowed for editable text.  android:autoLink Controls whether links such as urls and email addresses are automatically found and converted to clickable links.  android:autoSizeMaxTextSize The maximum text size constraint to be used when auto-sizing text.  android:autoSizeMinTextSize The minimum text size constraint to be used when auto-sizing text.  android:autoSizePresetSizes Resource array of dimensions to be used in conjunction with autoSizeTextType set to uniformandroid:autoSizeStepGranularity Specify the auto-size step size if autoSizeTextType is set to uniformandroid:autoSizeTextType Specify the type of auto-size.  android:autoText This is deprecated. Use inputType instead. May be a boolean value, such as "true" or "false".  android:breakStrategy Break strategy (control over paragraph layout).  android:bufferType Determines the minimum type that getText() will return.  android:capitalize This is deprecated. Use inputType instead.

Must be one of the following constant values.

ConstantValueDescription
characters3Capitalize every character.
none0Don't automatically capitalize anything.
sentences1Capitalize the first word of each sentence.
words2Capitalize the first letter of every word.
  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 This is deprecated. Use inputType instead. 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.  android:elegantTextHeight Elegant text height, especially for less compacted complex script text.  android:ellipsize If set, causes words that are longer than the view is wide to be ellipsized instead of broken in the middle.  android:ems Makes the TextView be exactly this many ems wide.  android:enabled Specifies whether the widget is enabled.  android:fallbackLineSpacing Whether to respect the ascent and descent of the fallback fonts that are used in displaying the text.  android:firstBaselineToTopHeight Distance from the top of the TextView to the first text baseline.  android:focusedSearchResultHighlightColor Color of focused search result highlight.  android:focusedSearchResultHighlightColor Color of focused search result highlight.  android:fontFamily Font family (named by string or as a font resource reference) for the text.  android:fontFeatureSettings Font feature settings.  android:fontVariationSettings Font variation settings.  android:freezesText If set, the text view will include its current complete text inside of its frozen icicle in addition to meta-data such as the current cursor position.  android:gravity Specifies how to align the text by the view's x- and/or y-axis when the text is smaller than the view.  android:height Makes the TextView be exactly this tall.  android:hint Hint text to display when the text is empty.  android:hyphenationFrequency Frequency of automatic hyphenation.  android:imeActionId Supply a value for EditorInfo.actionId used when an input method is connected to the text view.  android:imeActionLabel Supply a value for EditorInfo.actionLabel used when an input method is connected to the text view.  android:imeOptions Additional features you can enable in an IME associated with an editor to improve the integration with your application.  android:includeFontPadding Leave enough room for ascenders and descenders instead of using the font ascent and descent strictly.  android:inputMethod This is deprecated. Use inputType instead. May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character;  android:inputType The type of data being placed in a text field, used to help an input method decide how to let the user enter text.  android:justificationMode Mode for justification.  android:lastBaselineToBottomHeight Distance from the bottom of the TextView to the last text baseline.  android:letterSpacing Text letter-spacing.  android:lineBreakStyle Specifies the line-break strategies for text wrapping.  android:lineBreakWordStyle Specifies the line-break word strategies for text wrapping.  android:lineHeight Explicit height between lines of text.  android:lineSpacingExtra Extra spacing between lines of text.  android:lineSpacingMultiplier Extra spacing between lines of text, as a multiplier.  android:lines Makes the TextView be exactly this many lines tall.  android:linksClickable If set to false, keeps the movement method from being set to the link movement method even if autoLink causes links to be found.  android:marqueeRepeatLimit The number of times to repeat the marquee animation.  android:maxEms Makes the TextView be at most this many ems wide.  android:maxHeight Makes the TextView be at most this many pixels tall.  android:maxLength Set an input filter to constrain the text length to the specified number.  android:maxLines Makes the TextView be at most this many lines tall.  android:maxWidth Makes the TextView be at most this many pixels wide.  android:minEms Makes the TextView be at least this many ems wide.  android:minHeight Makes the TextView be at least this many pixels tall.  android:minLines Makes the TextView be at least this many lines tall.  android:minWidth Makes the TextView be at least this many pixels wide.  android:numeric This is deprecated. Use inputType instead.

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

ConstantValueDescription
decimal5Input is numeric, with decimals allowed.
integer1Input is numeric.
signed3Input is numeric, with sign allowed.
  android:password This is deprecated. Use inputType instead. May be a boolean value, such as "true" or "false".  android:phoneNumber This is deprecated. Use inputType instead. May be a boolean value, such as "true" or "false".  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:searchResultHighlightColor Color of search results highlight.  android:searchResultHighlightColor Color of search results highlight.  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 This is deprecated. This attribute is deprecated. Use maxLines instead to change the layout of a static text, and use the textMultiLine flag in the inputType attribute instead for editable text views (if both singleLine and inputType are supplied, the inputType flags will override the value of singleLine).

May be a boolean value, such as "true" or "false".  android:text Text to display.  android:textAllCaps Present the text in ALL CAPS.  android:textAppearance Base text color, typeface, size, and style.  android:textColor Text color.  android:textColorHighlight Color of the text selection highlight.  android:textColorHint Color of the hint text.  android:textColorLink Text color for links.  android:textCursorDrawable Reference to a drawable that will be drawn under the insertion cursor.  android:textFontWeight Weight for the font used in the TextView.  android:textIsSelectable Indicates that the content of a non-editable text can be selected.  android:textScaleX Sets the horizontal scaling factor for the text.  android:textSelectHandle Reference to a drawable that will be used to display a text selection anchor for positioning the cursor within text.  android:textSelectHandleLeft Reference to a drawable that will be used to display a text selection anchor on the left side of a selection region.  android:textSelectHandleRight Reference to a drawable that will be used to display a text selection anchor on the right side of a selection region.  android:textSize Size of the text.  android:textStyle Style (normal, bold, italic, bold|italic) for the text.  android:typeface Typeface (normal, sans, serif, monospace) for the text.  android:width Makes the TextView be exactly this wide. 

From class android.view.View android:accessibilityHeading Whether or not this view is a heading for accessibility purposes.  android:accessibilityLiveRegion Indicates to accessibility services whether the user should be notified when this view changes.  android:accessibilityPaneTitle The title this view should present to accessibility as a pane title.  android:accessibilityTraversalAfter Sets the id of a view that screen readers are requested to visit before this view.  android:accessibilityTraversalBefore Sets the id of a view that screen readers are requested to visit after this view.  android:allowClickWhenDisabled Whether or not allow clicks on disabled view.  android:alpha alpha property of the view, as a value between 0 (completely transparent) and 1 (completely opaque).  android:autoHandwritingEnabled Whether or not the auto handwriting initiation is enabled in this View.  android:autofillHints Describes the content of a view so that a autofill service can fill in the appropriate data.  android:autofilledHighlight Drawable to be drawn over the view to mark it as autofilled May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".  android:background A drawable to use as the background.  android:backgroundTint Tint to apply to the background.  android:backgroundTintMode Blending mode used to apply the background tint.  android:clickable Defines whether this view reacts to click events.  android:clipToOutline Whether the View's Outline should be used to clip the contents of the View.  android:contentDescription Defines text that briefly describes content of the view.  android:contextClickable Defines whether this view reacts to context click events.  android:defaultFocusHighlightEnabled Whether this View should use a default focus highlight when it gets focused but doesn't have R.attr.state_focused defined in its background.  android:drawingCacheQuality Defines the quality of translucent drawing caches.  android:duplicateParentState When this attribute is set to true, the view gets its drawable state (focused, pressed, etc.) from its direct parent rather than from itself.  android:elevation base z depth of the view.  android:fadeScrollbars Defines whether to fade out scrollbars when they are not in use.  android:fadingEdgeLength Defines the length of the fading edges.  android:filterTouchesWhenObscured Specifies whether to filter touches when the view's window is obscured by another visible window.  android:fitsSystemWindows Boolean internal attribute to adjust view layout based on system windows such as the status bar.  android:focusable Controls whether a view can take focus.  android:focusableInTouchMode Boolean that controls whether a view can take focus while in touch mode.  android:focusedByDefault Whether this view is a default-focus view.  android:forceHasOverlappingRendering Whether this view has elements that may overlap when drawn.  android:foreground Defines the drawable to draw over the content.  android:foregroundGravity Defines the gravity to apply to the foreground drawable.  android:foregroundTint Tint to apply to the foreground.  android:foregroundTintMode Blending mode used to apply the foreground tint.  android:hapticFeedbackEnabled Boolean that controls whether a view should have haptic feedback enabled for events such as long presses.  android:id Supply an identifier name for this view, to later retrieve it with View.findViewById() or Activity.findViewById()android:importantForAccessibility Describes whether or not this view is important for accessibility.  android:importantForAutofill Hints the Android System whether the view node associated with this View should be included in a view structure used for autofill purposes.  android:importantForContentCapture Hints the Android System whether the view node associated with this View should be use for content capture purposes.  android:isCredential This is deprecated. The isCredential attr is no longer needed. May be a boolean value, such as "true" or "false".  android:isScrollContainer Set this if the view will serve as a scrolling container, meaning that it can be resized to shrink its overall window so that there will be space for an input method.  android:keepScreenOn Controls whether the view's window should keep the screen on while visible.  android:keyboardNavigationCluster Whether this view is a root of a keyboard navigation cluster.  android:layerType Specifies the type of layer backing this view.  android:layoutDirection Defines the direction of layout drawing.  android:longClickable Defines whether this view reacts to long click events.  android:minHeight Defines the minimum height of the view.  android:minWidth Defines the minimum width of the view.  android:nextClusterForward Defines the next keyboard navigation cluster.  android:nextFocusDown Defines the next view to give focus to when the next focus is View.FOCUS_DOWN If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a RuntimeException will result when the reference is accessed.  android:nextFocusForward Defines the next view to give focus to when the next focus is View.FOCUS_FORWARD If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a RuntimeException will result when the reference is accessed.  android:nextFocusLeft Defines the next view to give focus to when the next focus is View.FOCUS_LEFTandroid:nextFocusRight Defines the next view to give focus to when the next focus is View.FOCUS_RIGHT If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a RuntimeException will result when the reference is accessed.  android:nextFocusUp Defines the next view to give focus to when the next focus is View.FOCUS_UP If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a RuntimeException will result when the reference is accessed.  android:onClick This is deprecated. View actually traverses the Context hierarchy looking for the relevant method, which is fragile (an intermediate ContextWrapper adding a same-named method would change behavior) and restricts bytecode optimizers such as R8. Instead, use View.setOnClickListener.

May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character;  android:outlineAmbientShadowColor Sets the color of the ambient shadow that is drawn when the view has a positive Z or elevation value.  android:outlineSpotShadowColor Sets the color of the spot shadow that is drawn when the view has a positive Z or elevation value.  android:padding Sets the padding, in pixels, of all four edges.  android:paddingBottom Sets the padding, in pixels, of the bottom edge; see R.attr.paddingandroid:paddingEnd Sets the padding, in pixels, of the end edge; see R.attr.paddingandroid:paddingHorizontal Sets the padding, in pixels, of the left and right edges; see R.attr.paddingandroid:paddingLeft Sets the padding, in pixels, of the left edge; see R.attr.paddingandroid:paddingRight Sets the padding, in pixels, of the right edge; see R.attr.paddingandroid:paddingStart Sets the padding, in pixels, of the start edge; see R.attr.paddingandroid:paddingTop Sets the padding, in pixels, of the top edge; see R.attr.paddingandroid:paddingVertical Sets the padding, in pixels, of the top and bottom edges; see R.attr.paddingandroid:preferKeepClear

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

Inherited constants

Inherited fields

Public constructors

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

Public methods

void extendSelection(int index)

Convenience for Selection.extendSelection.

CharSequence getAccessibilityClassName()

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

boolean getFreezesText()

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

Editable getText()

Return the text that TextView is displaying.

boolean isStyleShortcutEnabled()

Return true if style shortcut is enabled, otherwise returns false.

boolean onKeyShortcut(int keyCode, KeyEvent event)

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

boolean onTextContextMenuItem(int id)

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

void selectAll()

Convenience for Selection.selectAll.

void setEllipsize(TextUtils.TruncateAt ellipsis)

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

void setSelection(int index)

Convenience for Selection.setSelection(Spannable,int).

void setSelection(int start, int stop)

Convenience for Selection.setSelection(Spannable,int,int).

void setStyleShortcutsEnabled(boolean enabled)

Enables styls shortcuts, e.g. Ctrl+B for making text bold.

void setText(CharSequence text, TextView.BufferType type)

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

Protected methods

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.

Inherited methods

XML attributes

android:enableTextStylingShortcuts

Enables styling shortcuts, e.g. Ctrl+B for bold. This is off by default.

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

Public constructors

EditText

Added in API level 1
public EditText (Context context)

Parameters
context Context

EditText

Added in API level 1
public EditText (Context context, 
                AttributeSet attrs)

Parameters
context Context
attrs AttributeSet

EditText

Added in API level 1
public EditText (Context context, 
                AttributeSet attrs, 
                int defStyleAttr)

Parameters
context Context
attrs AttributeSet
defStyleAttr int

EditText

Added in API level 21
public EditText (Context context, 
                AttributeSet attrs, 
                int defStyleAttr, 
                int defStyleRes)

Parameters
context Context
attrs AttributeSet
defStyleAttr int
defStyleRes int

Public methods

extendSelection

Added in API level 1
public void extendSelection (int index)

Convenience for Selection.extendSelection.

Parameters
index 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

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.

getText

Added in API level 1
public Editable 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
Editable The text displayed by the text view.

isStyleShortcutEnabled

Added in API level 34
public boolean isStyleShortcutEnabled ()

Return true if style shortcut is enabled, otherwise returns false.

Returns
boolean true if style shortcut is enabled, otherwise returns 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.

onTextContextMenuItem

Added in API level 3
public boolean onTextContextMenuItem (int id)

Called when a context menu option for the text view is selected. Currently this will be one of R.id.selectAll, R.id.cut, R.id.copy, R.id.paste, R.id.pasteAsPlainText (starting at API level\u202f23) or R.id.shareText.

Parameters
id int
Returns
boolean true if the context menu item action was performed.

selectAll

Added in API level 1
public void selectAll ()

Convenience for Selection.selectAll.

setEllipsize

Added in API level 1
public void setEllipsize (TextUtils.TruncateAt ellipsis)

Causes words in the text that are longer than the view's width to be ellipsized instead of broken in the middle. TextUtils.TruncateAt#MARQUEE is not supported.

Parameters
ellipsis TextUtils.TruncateAt: Type of ellipsis to be applied.
Throws
IllegalArgumentException When the value of ellipsis parameter is TextUtils.TruncateAt.MARQUEE.

See also:

setSelection

Added in API level 1
public void setSelection (int index)

Convenience for Selection.setSelection(Spannable,int).

Parameters
index int

setSelection

Added in API level 1
public void setSelection (int start, 
                int stop)

Convenience for Selection.setSelection(Spannable,int,int).

Parameters
start int
stop int

setStyleShortcutsEnabled

Added in API level 34
public void setStyleShortcutsEnabled (boolean enabled)

Enables styls shortcuts, e.g. Ctrl+B for making text bold.

Parameters
enabled boolean: true for enabled, false for disabled.

setText

Added in API level 1
public void setText (CharSequence text, 
                TextView.BufferType type)

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

When required, TextView will use Spannable.Factory to create final or intermediate Spannables. Likewise it will use Editable.Factory to create final or intermediate Editables. Subclasses overriding this method should ensure that the following post condition holds, in order to guarantee the safety of the view's measurement and layout operations: regardless of the input, after calling #setText both mText and mTransformed will be different from null.

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

Protected methods

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