Text fields

Text fields let users enter and edit text.

Android check Web Flutter iOS

Interactive demo

This demo lets you preview the text field component, its variations, and configuration options. Each tab displays a different type of text field.


Usage

Text fields allow users to enter text into a UI. They typically appear in forms and dialogs.

Principles

Discoverable

Text fields should stand out and indicate that users can input information.

Clear

Text field states should be clearly differentiated from one another.

Efficient

Text fields should make it easy to understand the requested information and to address any errors.


Types

Text fields come in two forms: filled and outlined.

Text fields come in two types:

  • Filled text fields
  • Outlined text fields

Both types of text fields use a container to provide a clear affordance for interaction, making the fields discoverable in layouts.

2-part diagram showing the two types of text fields with two variations for each
1. Filled text fields
2. Outlined text fields

Choosing the right text field

Both types of text fields provide the same functionality, so the type of text field you use can depend on style alone. Choose the type...

Both types of text fields provide the same functionality, so the type of text field you use can depend on style alone.

Choose the type that:

  • Works best with your app’s visual style
  • Best accommodates the goals of your UI
  • Is most distinct from other components (like buttons) and surrounding content
A mobile UI for a contacts app form with many filled text fields
Mobile form using filled text fields
A mobile UI for a contacts app form with many outlined text fields
The same mobile form using outlined text fields

Both types of text fields in one UI

If both types of text fields are used in a single UI, they should be used consistently within different sections, and not intermixed within the same region. For example, you could use outlined text fields in one section and filled text fields in another.

Mobile UI with filled text fields at the top of the screen on a purple background and the lower two-thirds of the screen is a white background and outlined text fields
DoWhen using both types of text fields in a UI, separate them by region.
A mobile UI for a contact sheet and alternating styles of text fields in the same form
Don'tWhen using a both types of text fields, don't use both next to each other, or within the same form.

Anatomy

Filled text field anatomy diagram
1. Container
2. Leading icon (optional)
3. Label text
4. Input text
5. Trailing icon (optional)
6. Activation indicator
7. Helper text (optional)

Container

Containers improve the discoverability of text fields by creating contrast between the text field and surrounding content. A text field container has a fill and...

Containers improve the discoverability of text fields by creating contrast between the text field and surrounding content.

Fill and stroke

A text field container has a fill and a stroke (either around the entire container, or just the bottom edge). The color and thickness of a stroke can change to indicate when the text field is active.

Rounded corners

The container of an outlined text field has rounded corners, while the container of a filled text field has rounded top corners and square bottom corners.

Blank outlined and filled text fields. The outlined text field has a purple outline stroke. The filled text field has a grey fill and purple underline
Text field containers

Label text

Label text is used to inform users as to what information is requested for a text field. Every text field should have a label. Label...

Label text is used to inform users as to what information is requested for a text field. Every text field should have a label.

Label text should be aligned with the input line, and always visible. It can be placed in the middle of a text field, or rest near the top of the container.

DoLabel text should always be visible, moving from the middle of the text field to the top (if the field is selected).
Filled text field with text hidden by ellipsis
Don'tLabel text shouldn't be truncated. Keep it short, clear, and fully visible.
Filled text field with text taking up two lines
Don'tLabel text shouldn’t take up multiple lines.

Required text indicator

To indicate that a field is required, display an asterisk (*) next to the label text and mention near the form that asterisks indicate required fields.

  • If some fields are required, indicate all required ones
  • If most fields are required, indicate optional fields by displaying the word “optional” in parentheses next to the label text
  • If required text is colored, that color should also be used for the asterisk
Example form shows asterisk next to a username field in a form and helper text with the word “required” beneath the username field
Required text with asterisk

Input text

Input text is text the user has entered into a text field. Input text is text entered by the user. A cursor indicates the current...

Diagram of outlined text field. The outline and label are purple. The input text reads “Input text” followed by the cursor
Input text is text the user has entered into a text field.

1. Input text
Input text is text entered by the user.

2. Cursor
A cursor indicates the current location of text input in a field.

Assistive elements

Assistive elements provide additional detail about text entered into text fields. Helper text conveys additional guidance about the input field, such as how it will...

Diagram with three filled text fields. Top text field has “assistive text” below the text field. Middle text field 2 has “Error message” in red below the text field, a red alarm icon in the container to the right. Bottom text field has “Label” entered and character counter “5/20” below the container.
Assistive elements provide additional detail about text entered into text fields.

1. Helper text
Helper text conveys additional guidance about the input field, such as how it will be used. It should only take up a single line, being persistently visible or visible only on focus.

2. Error message
When text input isn't accepted, an error message can display instructions on how to fix it. Error messages are displayed below the input line, replacing helper text until fixed.

3. Icons
Icons can be used to message alerts as well. Pair them with error messages to provide redundant alerts, which are useful when you need to design for colorblind users.

4. Character counter
Character or word counters should be used if there is a character or word limit. They display the ratio of characters used and the total character limit.

Error text

For text fields that validate their content (such as passwords), replace helper text with error text when applicable. Swapping helper text with error text helps prevent new lines of text from being introduced into a layout, thus bumping content to fit it.

  • If only one error is possible, error text describes how to avoid the error
  • If multiple errors are possible, error text describes how to avoid the most likely error
DoSwap helper text with error text.
Don'tDon't place error text under helper text, as their appearance will shift content.
Long red error message below the text field wrapping two lines.
CautionLong errors can wrap to multiple lines if there isn't enough space to clearly describe the error. In this case, ensure padding between text fields is sufficient to prevent multi-lined errors from bumping layout content.

Icons

Icons in text fields are optional. Text field icons can describe valid input methods (such as a microphone icon), provide affordances to access additional functionality...

Icons in text fields are optional. Text field icons can describe valid input methods (such as a microphone icon), provide affordances to access additional functionality (such as clearing the content of a field), and can express an error.

Leading and trailing icons change their position based on LTR or RTL contexts.

1. Icon signifier
Icon signifiers can describe the type of input a text field requires, and be touch targets for nested components. For example, a calendar icon may be tapped to reveal a date picker.

2. Valid or error icon
Iconography can indicate both valid and invalid inputs, making error states clear for colorblind users.

3. Clear icon
Clear icons let users clear an entire input field. They appear only when input text is present.

4. Voice input icon
A microphone icon signifies that users can input characters using voice.

5. Dropdown icon
A dropdown arrow indicates that a text field has a nested selection component.

Behavior

Scaling and adaptation

As layouts adapt to larger screens and form factors, apply scalable container dimensions to text fields.

As layouts adapt to larger screens and form factors, apply flexible container dimensions to text fields. Set minimum and maximum values for margins, padding, and container dimensions as layouts scale so that typography adjusts for better reading experiences.

Text fields in a full-screen dialog on mobile, and simple dialog on tablet
Text fields can span the full width of the display on small screens, but should be bounded by flexible margins or other containers on larger screens.

As text fields expand within fluid layouts, avoid maintaining fixed margins and typography properties because this can lead to extra long text fields. Text fields should not, for example, span the full width of a large screen.


Filled text field

Usage

Filled text fields have more visual emphasis than outlined text fields, making them stand out when surrounded by other content and components.

Filled text fields have more visual emphasis than outlined text fields, making them stand out when surrounded by other content and components.

A filled text field
Filled text field with purple background and grey text
Don'tDon’t design text fields to look similar to buttons, as they could be mistaken for buttons.

Dense text fields

Dense text fields enable users to scan and take action on large amounts of information.

Dense text fields enable users to scan and take action on large amounts of information.

A form with dense text fields
1. Dense text field with a label
2. Dense text field without a label

Text fields without labels

A text field doesn’t require a label if the field’s purpose is indicated by a separate, adjacent label.

A text field doesn't require a label if the field's purpose is indicated by a separate, adjacent label.

Text fields with labels above each field
Text fields with adjacent labels

Prefix and suffix text

A text field with a currency symbol text prefix.
A text field with a unit of mass suffix.
Text field with a suffix expressing an academic grading scale.
Text field with an email domain address suffix.

States

Filled text fields (baseline)

Filled text fields can display the following states: inactive, activated, focused, hover, error, and disabled.

Filled text fields without labels

Filled text fields (without labels) can display the following states: inactive, activated, focused, hover, error, and disabled.

Filled text fields with prefix text

Filled text fields (with prefix text) can display the following states: inactive, activated, focused, hover, error, and disabled.

Filled text fields with suffix text

Filled text fields (with suffix text) can display the following states: inactive, activated, focused, hover, error, and disabled.

Outlined text field

Usage

Outlined text fields have less visual emphasis than filled text fields. When they appear in places like forms, where many text fields are placed together,...

Outlined text fields have less visual emphasis than filled text fields. When they appear in places like forms, where many text fields are placed together, their reduced emphasis helps simplify the layout.

An outlined text field

Dense text fields

Dense text fields enable users to scan and take action on large amounts of information.

Dense text fields enable users to scan and take action on large amounts of information.

A form with dense text fields
Dense text field, 40dp height

Text fields without labels

A text field doesn’t require a label if the field’s purpose is indicated by a separate, independent label.

A text field doesn't require a label if the field's purpose is indicated by a separate, independent label.

Form with separate labels above the inactive text fields
Text fields with separate but clear labels can indicate what the fields are for (title, price, and location).

Prefix and suffix text

A text field with a currency symbol prefix
A text field with a unit of mass suffix
A text field with grading scale as suffix
A text field with an email domain address suffix

States

Outlined text field (baseline)

Outlined text fields can display the following states: inactive, activated, focused, hover, error, and disabled.

Outlined text field without labels

Filled text fields can display the following states: inactive, activated, focused, hover, error, and disabled.

Outlined text field with prefix text

Filled text fields can display the following states: inactive, activated, focused, hover, error, and disabled.

Outlined text field with suffix text

Filled text fields can display the following states: inactive, activated, focused, hover, error, and disabled.

Input types

Text fields can display user input in the following ways:

  • Single line text fields display only one line of text
  • Multi-line text fields grow to accommodate multiple lines of text
  • Text areas are fixed-height fields
Single-line fields
In single-line fields, as the cursor reaches the right field edge, text longer than the input line automatically scrolls left.

Single-line fields are not suitable for collecting long responses. For those, use a multi-line text field or text area instead.
Multi-line fields
Multi-line text fields show all user input at once. Overflow text causes the text field to expand (shifting screen elements downward), and text wraps onto a new line.

These fields initially appear as single-line fields, which is useful for compact layouts that need to be able to accommodate large amounts of text.
Text areas
Text areas are taller than text fields and wrap overflow text onto a new line. They are a fixed height and scroll vertically when the cursor reaches the bottom of the field.

The large initial size indicates that longer responses are possible and encouraged.

These should be used instead of multi-line fields on the web. Ensure the height of a text area fits within mobile screen sizes.

Read-only fields

Read-only text fields display pre-filled text that the user cannot edit. A read-only text field is styled the same as a regular text field and is clearly labeled as read-only.

A filled read-only text field.
An outlined read-only text field.

Research

Material Design conducted two studies with around 600 participants to understand characteristics of text field usability and user preferences for text field design. The studies measured a user’s ability to scan and find a text field as well as the ability to identify the types of text fields.

Research showed the following are best practices that can be adopted to improve the usability of text fields:

  • Use an enclosed text field with a rectangular box, rather than a single underline to indicate a text field
  • Use either a semi-transparent fill with a bottom line or a fully transparent fill with an opaque stroke for the text field box
  • Place label text within the boundary of a text field box
  • Ensure text field outlines or strokes meet 3:1 minimum color contrast ratio to the background

Theming

Rally Material Theme

This personal finance app's filled text fields have been customized using Material Theming. Areas of customization include color and typography. Rally is a personal finance...

This personal finance app's filled text fields have been customized using Material Theming. Areas of customization include color and typography.

App screen with Rally logo and user name in a text field with checkmark
Rally's customized filled text fields

Color

Rally's filled text fields use custom color on five elements: label text, input text, trailing icon, activation indicator, and container.

Element Category Attribute Value
Label text Primary Color
Opacity
#FFFFFF
100%
Input text On Surface Color
Opacity
#FFFFFF
100%
Trailing icon On Surface Color
Opacity
#FFFFFF
100%
Activation indicator Primary Color
Opacity
#FFFFFF
100%
Container On Surface Color
Opacity
#FFFFFF
4%

Typography

Rally's filled text fields use custom typography for input text and label text.

Element Category Attribute Value
Input text Subtitle 1 Typeface
Font
Size
Case
Eczar
Regular
16
Title caps
Label text Caption Typeface
Font
Size
Case
Roboto Condensed
Regular
12
Title caps

Shape

Rally's filled text fields use custom corner shapes.

Element Category Attribute Value
Container Small component Family
Size
Cut
0;0;0;0 dp

Crane Material Theme

This travel app's outlined text fields have been customized using Material Theming. Areas of customization include color and typography. Crane is a travel app that...

This travel app's outlined text fields have been customized using Material Theming. Areas of customization include color and typography.

Crane's customized outlined text fields

Color

Crane's outlined text fields use custom color on three elements: the input text, label text, and container.

Element Category Attribute Value
Input text On Surface Color
Opacity
#000000
87%
Label Text On Surface Color
Opacity
#000000
60%
Container On Surface Color
Opacity
#000000
12%

Typography

Crane's outlined text fields use custom typography for the input text and label text.

Element Category Attribute Value
Input text Subtitle 1 Typeface
Font
Size
Case
Raleway
Medium
16
Title case
Label Text Caption Typeface
Font
Size
Case
Raleway
SemiBold
14
Title case

Shape

Crane's outlined text fields use custom corner shapes.

Element Category Attribute Value
Container Small component Family
Size
Cut
4;4;4;4 dp

Specs

Filled text field

16dp #00000099 12dp #00000099 #0000a R0 G0 B10 Elevation 0dp Top left, top right corner Rounded: 4dp All measurements are displayed in device-independent pixels (dps)...


Outlined text field

12dp #00000099 All measurements are displayed in device-independent pixels (dps) 16dp #3c4043 12dp #6200ee #00000060 R0 G0 B0 A0.38 Elevation 0dp All corners Rounded: 4dp...

Using text fields

Before you can use Material text fields, you need to add a dependency to the Material Components for Android library. For more information, go to the Getting started page.

Note: A text field is composed of a TextInputLayout and a TextInputEditText as a direct child. Using an EditText as the child might work, but TextInputEditText provides accessibility support for the text field and allows TextInputLayout greater control over the visual aspects of the input text. If an EditText is being used, make sure to set its android:background to @null so that TextInputLayout can set the proper background on it.

Making text fields accessible

Android's text field component APIs support both label text and helper text for informing the user as to what information is requested for a text field. While optional, their use is strongly encouraged.

Content description

When using custom icons, you should set a content description on them so that screen readers like TalkBack are able to announce their purpose or action, if any.

For the leading icon, that can be achieved via the app:startIconContentDescription attribute or setStartIconContentDescription method. For the trailing icon, that can be achieved via the app:endIconContentDescription attribute or setEndIconContentDescription method.

When setting an error message that contains special characters that screen readers or other accessibility systems are not able to read, you should set a content description via the app:errorContentDescription attribute or setErrorContentDescription method. That way, when the error needs to be announced, it will announce the content description instead.

Custom EditText

If you are using a custom EditText as TextInputLayout's child and your text field requires different accessibility support than the one offered by TextInputLayout, you can set a TextInputLayout.AccessibilityDelegate via the setTextInputAccessibilityDelegate method. This method should be used in place of providing an AccessibilityDelegate directly on the EditText.

Adding a leading icon to a text field

"Text field with a leading icon."

Adding a trailing icon to a text field

Password toggle:

"Text field with a password toggle trailing icon."

If set, an icon is displayed to toggle between the password being displayed as plain-text or disguised (when the TextInputEditText is set to display a password).

Clear text:

"Text field with a clear text trailing icon."

If set, an icon is displayed when text is present and pressing it clears the input text.

Custom icon:

"Text field with a custom trailing icon."

It is possible to set a custom Drawable as the text field's trailing icon via app:endIconMode="custom". You should specify a drawable and content description for the icon, and, optionally, specify custom behaviors.

In the layout:

Optionally, in code:

Note: You should opt to use the EndIconMode API instead of setting an end/right compound Drawable on the TextInputEditText. The same applies to the now-deprecated passwordToggle* attributes.

See the full list of end icon modes.

Implementing an exposed dropdown menu

"Text field with an exposed dropdown menu."

In the layout:

In code:

In the item layout (list_item.xml):

Adding helper text to a text field

"Text field with helper text."

Adding a counter to a text field

"Text field with a counter."

Adding errors to a text field

"Text field with an error."

In the layout:

In code:

Note: Non-null error text will replace any existing helper text.

Adding a prefix/suffix to a text field

"Text field with a prefix/suffix."

Text field dimensions

The recommended default android:layout_width is 245dp.

By default, text fields have a maximum width of 488dp, and a minimum width of 56dp for layouts without a label. If a label is present, the minimum width recommended is 88dp. android:minWidth and android:maxWidth should be set on the TextInputLayout instead of on the TextInputEditText to avoid unintended behaviors.

You can override those values in a custom style that inherits from a TextInputLayout style or directly on the layout:

Note: The android:layout_width of the TextInputLayout should be wrap_content in order for those minimum and maximum dimensions to be used.

Using text fields programmatically

If you construct the TextInputEditText child of a TextInputLayout programmatically, you should use TextInputLayout's context to create the view. This will allow TextInputLayout to pass along the appropriate styling to the edit text.

Types

There are two types of text fields: 1. Filled text field, 2. Outlined text field

"Text field types. Fixed: grey back, dark gray indicator turns purple.
Outlined: clear back, gray outline turns
purple"

Filled text field

Filled text fields have more visual emphasis than outlined text fields, making them stand out when surrounded by other content and components.

Note: The filled text field is the default style if the style is not set.

Filled text field examples

API and source code:

The following examples shows a filled text field with a label.

Filled text field

In the layout:

In code:

See the using text fields section above for more examples.

Anatomy and key properties

A filled text field has a filled container, input text, a label, an activation indicator, optional helper/error text and optional leading/trailing icons.

Filled text field anatomy

  1. Container
  2. Leading icon
  3. Label
  4. Input text
  5. Trailing icon
  6. Activation indicator
  7. Helper/error/counter text
  8. Prefix/suffix/placeholder (not shown)

Note: All the attributes on the tables below should be set on the TextInputLayout, with the exception of the input text attributes (which should be set on the TextInputEditText).

Container attributes

ElementAttributeRelated method(s)Default value
Colorapp:boxBackgroundColorsetBoxBackgroundColor
setBoxBackgroundColorResource
getBoxBackgroundColor
?attr/colorOnSurface at 12% opacity (see all states)
Shapeapp:shapeAppearanceN/A?attr/shapeAppearanceSmallComponent
Text field enabledandroid:enabledsetEnabledtrue

Leading icon attributes

ElementAttributeRelated method(s)Default value
Iconapp:startIconDrawablesetStartIconDrawable
getStartIconDrawable
null
Content descriptionapp:startIconContentDescriptionsetStartIconContentDescription
getStartIconContentDescription
null
Colorapp:startIconTintsetStartIconTintListcolorOnSurface at 54% opacity (see all states)
Checkableapp:startIconCheckablesetStartIconCheckable
isStartIconCheckable
false

Label attributes

ElementAttributeRelated method(s)Default value
Textandroid:hintsetHint
getHint
null
Colorandroid:textColorHintsetDefaultHintTextColor
getDefaultHintTextColor
?attr/colorOnSurface at 60% opacity (see all states)
Collapsed (floating) colorapp:hintTextColorsetHintTextColor
getHintTextColor
?attr/colorPrimary
Typographyapp:hintTextAppearancesetHintTextAppearance?attr/textAppearanceCaption
Animationapp:hintAnimationEnabledsetHintAnimationEnabled
isHintAnimationEnabled
true
Expanded enabledapp:expandedHintEnabledsetExpandedHintEnabled
isExpandedHintEnabled
true

Note: The android:hint should always be set on the TextInputLayout instead of on the EditText in order to avoid unintended behaviors.

Input text attributes

ElementAttributeRelated method(s)Default value
Input textandroid:textsetText
getText
@null
Typographyandroid:textAppearancesetTextAppearance?attr/textAppearanceSubtitle1
Input text colorandroid:textColorsetTextColor
getTextColors
getCurrentTextColor
?android:textColorPrimary
Cursor colorN/A (color comes from the theme attr ?attr/colorControlActivated)N/A?attr/colorPrimary

Note: The input text attributes should be set on the TextInputEditText.

Trailing icon attributes

ElementAttributeRelated method(s)Default value
Modeapp:endIconModesetEndIconMode
getEndIconMode
END_ICON_NONE
Colorapp:endIconTintsetEndIconTintListcolorOnSurface at 54% opacity and colorPrimary (activated) (see all states)
Custom iconapp:endIconDrawablesetEndIconDrawable
getEndIconDrawable
null
Custom icon content descriptionapp:endIconContentDescriptionsetEndIconContentDescription
getEndIconContentDescription
null
Custom icon checkableapp:endIconCheckablesetEndIconCheckable
isEndIconCheckable
true
Error iconapp:errorIconDrawablesetErrorIconDrawable
getErrorIconDrawable
@drawable/mtrl_ic_error
Error icon colorapp:errorIconTintsetErrorIconTintList?attr/colorError (see all states)

Activation indicator attributes

ElementAttributeRelated method(s)Default value
Colorapp:boxStrokeColorsetBoxStrokeColor
setBoxStrokeColorStateList
getBoxStrokeColor
?attr/colorOnSurface at 42% opacity and ?attr/colorPrimary (focused) (see all states)
Error colorapp:boxStrokeErrorColorsetBoxStrokeErrorColor
getBoxStrokeErrorColor
?attr/colorError (see all states)
Widthapp:boxStrokeWidthN/A1dp
Focused widthapp:boxStrokeWidthFocusedN/A2dp

Helper/error/counter text attributes

ElementAttributeRelated method(s)Default value
Helper text enabledapp:helperTextEnabledsetHelperTextEnabled
isHelperTextEnabled
false
Helper textapp:helperTextsetHelperText
getHelperText
null
Helper text colorapp:helperTextColorsetHelperTextColor
getHelperTextColor
?attr/colorOnSurface at 60% opacity (see all states)
Helper text typographyapp:helperTextAppearancesetHelperTextAppearance?attr/textAppearanceCaption
Error text enabledapp:errorEnabledsetErrorEnabled
isErrorEnabled
false
Error textN/AsetError
getError
null
Error text colorapp:errorTextColorsetErrorTextColor
getErrorCurrentTextColors
?attr/colorError (see all states
Error text typographyapp:errorTextAppearancesetErrorTextAppearance?attr/textAppearanceCaption
Counter text enabledapp:counterEnabledsetCounterEnabled
isCounterEnabled
false
Counter text lengthapp:counterMaxLengthsetCounterMaxLength
getCounterMaxLength
-1
Counter text typographyapp:counterTextAppearance
app:counterOverflowTextAppearance
setCounterTextAppearance
setCounterOverflowTextAppearance
?attr/textAppearanceCaption
Counter text colorapp:counterTextColor
app:counterOverflowTextColor
setCounterTextColor
setCounterOverflowTextColor
getCounterTextColor
getCounterOverflowTextColor
?attr/colorOnSurface at 60% (app:counterTextColor) (see all states)
?attr/colorError (app:counterOverflowTextColor) (see all states

Prefix/suffix attributes

ElementAttributeRelated method(s)Default value
Prefixapp:prefixTextsetPrefixText
getPrefixText
null
Prefix colorapp:prefixTextColorsetPrefixTextColor
getPrefixTextColor
?attr/colorOnSurface at 60% opacity (see all states)
Prefix typographyapp:prefixTextAppearancesetPrefixTextAppearance?attr/textAppearanceSubtitle1
Suffixapp:suffixTextsetSuffixText
getSuffixText
null
Suffix colorapp:suffixTextColorsetSuffixTextColor
getSuffixTextColor
?attr/colorOnSurface at 60% opacity (see all states)
Suffix typographyapp:suffixTextAppearancesetSuffixTextAppearance?attr/textAppearanceSubtitle1

Styles

ElementStyle
Default styleWidget.MaterialComponents.TextInputLayout.FilledBox
Dense styleWidget.MaterialComponents.TextInputLayout.FilledBox.Dense
Exposed dropdown menu styleWidget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu
Dense exposed dropdown menu styleWidget.MaterialComponents.TextInputLayout.FilledBox.Dense.ExposedDropdownMenu

Default style theme attribute: ?attr/textInputStyle

See the full list of styles and attrs.

Outlined text field

Outlined text fields have less visual emphasis than filled text fields. When they appear in places like forms, where many text fields are placed together, their reduced emphasis helps simplify the layout.

Outlined text field examples

API and source code:

The following examples shows an outlined text field.

Outlined text field

In the layout:

In code:

See the using text fields section above for more examples.

Anatomy and key properties

An outlined text field has a stroked container, input text, a label, optional helper/error text and optional leading/trailing icons.

Outlined text field anatomy

  1. Container
  2. Leading icon
  3. Label
  4. Input text
  5. Trailing icon
  6. Helper/error/counter text
  7. Prefix/suffix/placeholder (not shown)

Note: All the attributes on the tables below should be set on the TextInputLayout, with the exception of the input text attributes (which should be set on the TextInputEditText).

Container attributes

ElementAttributeRelated method(s)Default value
Stroke colorapp:boxStrokeColorsetBoxStrokeColor
setBoxStrokeColorStateList
getBoxStrokeColor
?attr/colorOnSurface at 38% opacity and ?attr/colorPrimary (focused) (see all states)
Stroke error colorapp:boxStrokeErrorColorsetBoxStrokeErrorColor
getBoxStrokeErrorColor
?attr/colorError (see all states)
Stroke widthapp:boxStrokeWidthN/A1dp
Stroke focused widthapp:boxStrokeWidthFocusedN/A2dp
Shapeapp:shapeAppearanceN/A?attr/shapeAppearanceSmallComponent
Text field enabledandroid:enabledsetEnabledtrue

Leading icon attributes

ElementAttributeRelated method(s)Default value
Iconapp:startIconDrawablesetStartIconDrawable
getStartIconDrawable
null
Content descriptionapp:startIconContentDescriptionsetStartIconContentDescription
getStartIconContentDescription
null
Colorapp:startIconTintsetStartIconTintListcolorOnSurface at 60% opacity (see all states)
Checkableapp:startIconCheckablesetStartIconCheckable
isStartIconCheckable
false

Label attributes

ElementAttributeRelated method(s)Default value
Textandroid:hintsetHint
getHint
null
Colorandroid:textColorHintsetDefaultHintTextColor
getDefaultHintTextColor
?attr/colorOnSurface at 60% opacity (see all states)
Collapsed (floating) colorapp:hintTextColorsetHintTextColor
getHintTextColor
?attr/colorPrimary
Typographyapp:hintTextAppearancesetHintTextAppearance?attr/textAppearanceCaption

Note: The android:hint should always be set on the TextInputLayout instead of on the EditText in order to avoid unintended behaviors.

Input text attributes

ElementAttributeRelated method(s)Default value
Input textandroid:textsetText
getText
@null
Typographyandroid:textAppearancesetTextAppearance?attr/textAppearanceSubtitle1
Input text colorandroid:textColorsetTextColor
getTextColors
getCurrentTextColor
?android:textColorPrimary
Cursor colorN/A (color comes from the theme attr ?attr/colorControlActivated)N/A?attr/colorPrimary

Note: The input text attributes should be set on the TextInputEditText.

Trailing icon attributes

ElementAttributeRelated method(s)Default value
Modeapp:endIconModesetEndIconMode
getEndIconMode
END_ICON_NONE
Colorapp:endIconTintsetEndIconTintListcolorOnSurface at 60% opacity and colorPrimary (activated) (see all states)
Custom iconapp:endIconDrawablesetEndIconDrawable
getEndIconDrawable
null
Custom icon content descriptionapp:endIconContentDescriptionsetEndIconContentDescription
getEndIconContentDescription
null
Custom icon checkableapp:endIconCheckablesetEndIconCheckable
isEndIconCheckable
true
Error iconapp:errorIconDrawablesetErrorIconDrawable
getErrorIconDrawable
@drawable/mtrl_ic_error
Error icon colorapp:errorIconTintsetErrorIconTintList?attr/colorError (see all states)

Helper/error/counter text attributes

ElementAttributeRelated method(s)Default value
Helper text enabledapp:helperTextEnabledsetHelperTextEnabled
isHelperTextEnabled
false
Helper textapp:helperTextsetHelperText
getHelperText
null
Helper text colorapp:helperTextColorsetHelperTextColor
getHelperTextColor
?attr/colorOnSurface at 60% opacity (see all states)
Helper text typographyapp:helperTextAppearancesetHelperTextAppearance?attr/textAppearanceCaption
Error text enabledapp:errorEnabledsetErrorEnabled
isErrorEnabled
false
Error textN/AsetError
getError
null
Error text colorapp:errorTextColorsetErrorTextColor
getErrorCurrentTextColors
?attr/colorError (see all states
Error text typographyapp:errorTextAppearancesetErrorTextAppearance?attr/textAppearanceCaption
Counter text enabledapp:counterEnabledsetCounterEnabled
isCounterEnabled
false
Counter text lengthapp:counterMaxLengthsetCounterMaxLength
getCounterMaxLength
-1
Counter text typographyapp:counterTextAppearance
app:counterOverflowTextAppearance
setCounterTextAppearance
setCounterOverflowTextAppearance
?attr/textAppearanceCaption
Counter text colorapp:counterTextColor
app:counterOverflowTextColor
setCounterTextColor
setCounterOverflowTextColor
getCounterTextColor
getCounterOverflowTextColor
?attr/colorOnSurface at 60% (app:counterTextColor) (see all states)
?attr/colorError (app:counterOverflowTextColor) (see all states)

Prefix/suffix attributes

ElementAttributeRelated method(s)Default value
Prefixapp:prefixTextsetPrefixText
getPrefixText
null
Prefix colorapp:prefixTextColorsetPrefixTextColor
getPrefixTextColor
?attr/colorOnSurface at 60% opacity (see all states)
Prefix typographyapp:prefixTextAppearancesetPrefixTextAppearance?attr/textAppearanceSubtitle1
Suffixapp:suffixTextsetSuffixText
getSuffixText
null
Suffix colorapp:suffixTextColorsetSuffixTextColor
getSuffixTextColor
?attr/colorOnSurface at 60% opacity (see all states)
Suffix typographyapp:suffixTextAppearancesetSuffixTextAppearance?attr/textAppearanceSubtitle1

Styles

ElementStyle
Default styleWidget.MaterialComponents.TextInputLayout.OutlinedBox
Dense styleWidget.MaterialComponents.TextInputLayout.OutlinedBox.Dense
Exposed dropdown menu styleWidget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu
Dense exposed dropdown menu styleWidget.MaterialComponents.TextInputLayout.OutlinedBox.Dense.ExposedDropdownMenu

Default style theme attribute: ?attr/textInputStyle

See the full list of styles and attrs.

Theming text fields

Text fields support Material Theming and can be customized in terms of color, typography and shape.

Text field theming example

API and source code:

The following example shows filled and outlined text field types with Material Theming.

"Filled and outlined text field theming with pink and brown colors and cut
corners"

Implementing text field theming

Using theme attributes and styles in res/values/styles.xml (themes all text fields and affects other components):

or using default style theme attributes, styles and theme overlays (themes all text fields but does not affect other components):

or using one the style in the layout (affects only this text field):

Note: When setting a materialThemeOverlay on a custom TextInputLayout style, don't forget to set editTextStyle to either a @style/Widget.MaterialComponents.TextInputEditText.* style or to a custom one that inherits from that.
The TextInputLayout styles set materialThemeOverlay that overrides editTextStyle with the specific TextInputEditText style needed. Therefore, you don't need to specify a style tag on the edit text.

No Android implementation guidance available

Using text fields

Text fields allow users to enter text into a UI. They typically appear in forms and dialogs.

Installation

Styles

JavaScript instantiation

Note: See Importing the JS component for more information on how to import JavaScript.

Filled text

Filled text fields have more visual emphasis than outlined text fields, making them stand out when surrounded by other content and components.

Filled text example

Outlined text

Outlined text fields have less visual emphasis than filled text fields. When they appear in places like forms, where many text fields are placed together, their reduced emphasis helps simplify the layout.

Outlined text example

See here for more information on using the notched outline sub-component.

Note: Do not use mdc-line-ripple inside of mdc-text-fieldif you plan on using mdc-text-field--outlined. Line Ripple should not be included as part of the DOM structure of an outlined text field.

Other variations

Textarea

Filled

Outlined

Note: The mdc-text-field__resizer element may be omitted for a non-resizable textarea.

Text field without label

A text field doesn’t require a label if a separate but clear label indicator is already displayed adjacent to the text field. Add class name mdc-text-field--no-label and remove the label element from the structure.

Filled

Outlined

Textarea

Disabled text field

To disable the text field, add the disabled attribute to the <input> element and add the mdc-text-field--disabled class to the mdc-text-field element.

Text field with helper text

The helper text provides supplemental information and/or validation messages to users. It appears on input field focus and disappears on input field blur by default, or it can be persistent. Helper text should be rendered inside .mdc-text-field-helper-line element which is immediate sibling of .mdc-text-field. See here for more information on using helper text.

Text field with character counter

Character counter is used if there is a character limit. It displays the ratio of characters used and the total character limit. Character counter should be rendered inside .mdc-text-field-helper-line element which is immediate sibling of .mdc-text-field. See here for more information on using character counter.

Multi-line text field (textarea) with character counter

A character counter can be associated with a textarea by including it in the helper line. In this case, the counter will appear below the textarea, adjacent to any helper text.

Alternatively, the character counter can be placed in the textarea's body by inserting the character counter below the textarea and adding the mdc-text-field--with-internal-counter modifier class to the text field.

Helper text and Character counter are optional subcomponents of text field that can co-exist independently. It is recommended that .mdc-text-field and .mdc-text-field-helper-line elements have same width for correct layout.

Text field with prefix and suffix text

Prefix and suffix text can add context to a text field, such as a currency symbol prefix or a unit of mass suffix. A prefix, suffix, or both can be added within the default or outlined variants of text fields.

Note: Do not use mdc-text-field--affix within mdc-text-field--textarea.

Text field with leading and trailing icons

Leading and trailing icons can be added within the default or outlined variant of MDC Text Field as visual indicators as well as interaction targets. See here for more information on using icons.

Other features

HTML5 validation

MDCTextFieldFoundation provides validity styling by using the :invalid and :required attributes provided by HTML5's form validation API.

MDCTextFieldFoundation automatically appends an asterisk to the label text if the required attribute is set.

Pre-filled

When dealing with JS-driven text fields that already have values, you'll want to ensure that you render mdc-text-field with the mdc-text-field--label-floating modifier class, as well as mdc-floating-label with the mdc-floating-label--float-above modifier class. This will ensure that the label moves out of the way of the text field's value and prevents a Flash Of Un-styled Content (FOUC).

Baseline alignment

By default, text fields will be aligned with other elements relative to their baseline. The input text's baseline is used to determine where a text field should be aligned to and is different between variants. To force alignment to the text field's container instead of its baseline, align the element using flexbox.

API

CSS classes

CSS ClassDescription
mdc-text-fieldMandatory.
mdc-text-field--filledStyles the text field as a filled text field.
mdc-text-field--outlinedStyles the text field as an outlined text field.
mdc-text-field--textareaIndicates the text field is a <textarea>.
mdc-text-field--disabledStyles the text field as a disabled text field.
mdc-text-field--with-leading-iconStyles the text field as a text field with a leading icon.
mdc-text-field--with-trailing-iconStyles the text field as a text field with a trailing icon.
mdc-text-field--focusedStyles the text field as a text field in focus.
mdc-text-field--no-labelStyles the text field that has no label.
mdc-text-field--end-alignedStyles the text field with an end-aligned input.
mdc-text-field--label-floatingStyles the text field with a floating label and pre-filled or focused value.
mdc-text-field--ltr-textStyles the text field's text elements (input, prefix, and suffix) as LTR even when the direction is RTL. Useful for RTL languages that use LTR for fractional notations.
mdc-text-field--with-internal-counterStyles the text area as a text area with an internal character counter.
mdc-text-field-helper-lineStyles the container of helper text and character counter elements.

Sass mixins

To customize the colors of any part of the text-field, use the following mixins. We recommend you apply these mixins within CSS selectors like .foo-text-field:not(.mdc-text-field--focused) to select your unfocused text fields, and .foo-text-field.mdc-text-field--focused to select your focused text-fields. To change the invalid state of your text fields, apply these mixins with CSS selectors such as .foo-text-field.mdc-text-field--invalid.

NOTE: the mdc-line-ripple-color mixin should be applied from the not focused class foo-text-field:not(.mdc-text-field--focused)).

Mixins for all text fields

MixinDescription
ink-color($color)Customizes the color of the text entered into an enabled text field.
placeholder-color($color)Customizes the color of the placeholder in an enabled text field.
disabled-ink-color($color)Customizes the color of the entered text in a disabled text field.
disabled-placeholder-color($color)Customizes the color of the placeholder in a disabled text field.
label-color($color)Customizes the text color of the label in an enabled text field.
disabled-label-color($color)Customizes the text color of the label in a disabled text field.
caret-color($color)Customizes the color of the cursor caret of the text field.
prefix-color($color)Customizes the color of the prefix text of an enabled text field.
disabled-prefix-color($color)Customizes the color of the prefix text of a disabled text field.
suffix-color($color)Customizes the color of the suffix text of an enabled text field.
disabled-suffix-color($color)Customizes the color of the suffix text of a disabled text field.
floating-label-float-transition($duration-ms, $timing-function)Customizes the duration and optional timing function for the floating label's "float" transition.

Mixins for filled text field and textarea

MixinDescription
fill-color($color)Customizes the background color of the text field or textarea when enabled.
disabled-fill-color($color)Customizes the background color of the text field or textarea when disabled.

Mixins for filled text field only

MixinDescription
shape-radius($radius, $rtl-reflexive)Sets rounded shape to boxed text field variant with given radius size. Set $rtl-reflexive to true to flip radius values in RTL context, defaults to false.
bottom-line-color($color)Customizes the text field bottom line color.
hover-bottom-line-color($color)Customizes the hover text field bottom line color.
disabled-bottom-line-color($color)Customizes the disabled text field bottom line color.
line-ripple-color($color)Customizes the color of the default line ripple of the text field.
density($density-scale)Sets density scale for default text field variant. Supported density scale values -4, -3, -2, -1, 0.
height($height)Sets height of default text field variant.

Mixins for outlined text field and textarea

MixinDescription
focused-outline-color($color)Customizes the outline border color when the text field or textarea is focused.
hover-outline-color($color)Customizes the outline border color when the text field or textarea is hovered.
disabled-outline-color($color)Customizes the outline border color when the text field or textarea is disabled.
outline-color($color)Customizes the border color of the outlined text field or textarea.

Mixins for outlined text field only

MixinDescription
outline-shape-radius($radius, $rtl-reflexive)Sets rounded shape to outlined text field variant with given radius size. Set $rtl-reflexive to true to flip radius values in RTL context, defaults to false.
outlined-density($density-scale)Sets density scale for outlined text field (Excluding outlined text field with leading icon). Supported density scale values -4, -3, -2, -1, 0.
outlined-height($height)Sets height of outlined text field variant (Excluding outlined text field with leading icon).
outlined-with-leading-icon-density($density-scale)Sets density scale for outlined text field with leading icon. Supported density scale values -4, -3, -2, -1, 0.
outlined-with-leading-icon-height($height)Sets height of outlined text field with leading icon variant.

Mixins for textarea only

MixinDescription
textarea-shape-radius($radius, $rtl-reflexive)Sets rounded shape to text area variant with given radius size. Set $rtl-reflexive to true to flip radius values in RTL context, defaults to false.
outlined-textarea-density($density-scale)Sets density scale for outlined textarea. Supported density scale values -4, -3, -2, -1, 0.
textarea-min-rows($rows)Sets the minimum number of rows for a textarea a textarea may be resized to.

MDCTextField properties and methods

PropertyValue TypeDescription
valuestringProxies to the foundation's getValue/setValue methods.
disabledbooleanProxies to the foundation's isDisabled/setDisabled methods.
useNativeValidationboolean (write-only)Proxies to the foundation's setUseNativeValidation method.
validbooleanProxies to the foundation's isValid/setValid methods.
helperTextContentstring (write-only)Proxies to the foundation's setHelperTextContent method when set.
rippleMDCRipple (write-only)The MDCRipple instance for the root element that MDCTextField initializes; this only applies to the default Text Field, and is null for other variants.
leadingIconAriaLabelstring (write-only)Proxies to the foundation's setLeadingIconAriaLabel method.
trailingIconAriaLabelstring (write-only)Proxies to the foundation's setTrailingIconAriaLabel method.
leadingIconContentstring (write-only)Proxies to the foundation's setLeadingIconContent method.
trailingIconContentstring (write-only)Proxies to the foundation's setTrailingIconContent method.
prefixTextstringGets or sets the text content of the prefix, if it exists.
suffixTextstringGets or sets the text content of the suffix, if it exists.

In addition to the above, the following properties proxy to the input element's properties of the same name:

  • required
  • pattern
  • minLength
  • maxLength
  • min
  • max
  • step
Method SignatureDescription
focus() => voidFocuses the input or textarea element.
layout() => voidAdjusts the dimensions and positions for all sub-elements.

Usage within frameworks

If you are using a JavaScript framework, such as React or Angular, you can create a Text Field for your framework. Depending on your needs, you can use the Simple Approach: Wrapping MDC Web Vanilla Components, or the Advanced Approach: Using Foundations and Adapters. Please follow the instructions here.

MDCTextFieldAdapter

Method SignatureDescription
addClass(className: string) => voidAdds a class to the root element.
removeClass(className: string) => voidRemoves a class from the root element.
hasClass(className: string) => booleanReturns true if the root element contains the given class name.
registerTextFieldInteractionHandler(evtType: string, handler: EventListener) => voidRegisters an event handler on the root element for a given event.
deregisterTextFieldInteractionHandler(evtType: string, handler: EventListener) => voidDeregisters an event handler on the root element for a given event.
registerInputInteractionHandler(evtType: string, handler: EventListener) => voidRegisters an event listener on the native input element for a given event.
deregisterInputInteractionHandler(evtType: string, handler: EventListener) => voidDeregisters an event listener on the native input element for a given event.
registerValidationAttributeChangeHandler(handler: (attributeNames: string[]) => void) => MutationObserverRegisters a validation attribute change listener on the input element. Handler accepts list of attribute changes.
deregisterValidationAttributeChangeHandler(!MutationObserver) => voidDisconnects a validation attribute observer on the input element.
getNativeInput() => NativeInputType | nullReturns an object representing the native text input element, with a similar API shape. See types.ts.
isFocused() => booleanReturns whether the input is focused.
shakeLabel(shouldShake: boolean) => voidShakes the label to indicate an invalid input value.
floatLabel(shouldFloat: boolean) => voidFloats the label.
hasLabel() => booleanDetermines whether the text field has a label element.
getLabelWidth() => numberReturns the width of the label element in px.
activateLineRipple() => voidActivates the text field's line ripple sub-element.
deactivateLineRipple() => voidDeactivate the text field's line ripple sub-element.
setLineRippleTransformOrigin(normalizedX: number) => voidSets the CSS transform-origin property to the given value on the text field's line ripple sub-element (if present).
hasOutline() => booleanDetermines whether the text field has an outline sub-element.
notchOutline(labelWidth: number) => voidSets the width of the text field's notched outline sub-element.
closeOutline() => voidCloses the text field's notched outline sub-element.

MDCTextFieldAdapter.getNativeInput()

Returns an object representing the native text input element, with a similar API shape. We never alter the value within our code, however we do update the disabled property, so if you choose to duck-type the return value for this method in your implementation it's important to keep this in mind. Also note that this method can return null, which the foundation will handle gracefully.

MDCTextFieldAdapter.getIdleOutlineStyleValue(propertyName: string)

Returns the idle outline element's computed style value of the given css property propertyName. The vanilla implementation achieves this via getComputedStyle(...).getPropertyValue(propertyName).

MDCTextFieldFoundation

PropertyValue TypeDescription
shouldFloatboolean (read-only)Determines whether the label should float.
shouldShakeboolean (read-only)Determines whether the label should shake.
Method SignatureDescription
getValue() => stringReturns the input's value.
setValue(value: string)Sets the input's value.
setUseNativeValidation(useNativeValidation: boolean)Sets whether to check native HTML validity state (true, default) or custom validity state when updating styles (false).
setValid(isValid: boolean)Sets custom validity and updates styles accordingly. Note that native validation will still be honored subsequently unless setUseNativeValidation(false) is also called.
isValid() => booleanReturns the component's current validity state (either native or custom, depending on how setUseNativeValidation() was configured).
isDisabled() => booleanReturns whether or not the input is disabled.
setDisabled(disabled: boolean) => voidUpdates the input's disabled state.
handleTextFieldInteraction(evt: Event) => voidHandles click and keydown events originating from inside the Text Field component.
handleInput() => voidHandles text input and textarea input event.
handleValidationAttributeChange(attributesList: !Array<string>) => voidHandles validation attribute changes.
activateFocus() => voidActivates the focus state of the Text Field. Normally called in response to the input focus event.
deactivateFocus() => voidDeactivates the focus state of the Text Field. Normally called in response to the input blur event.
setHelperTextContent(content: string) => voidSets the content of the helper text.
setLeadingIconAriaLabel(label: string) => voidSets the aria label of the leading icon.
setLeadingIconContent(content: string) => voidSets the text content of the leading icon.
setTrailingIconAriaLabel(label: string) => voidSets the aria label of the trailing icon.
setTrailingIconContent(content: string) => voidSets the text content of the trailing icon.
notchOutline(openNotch: boolean) => voidOpens/closes the notched outline.
setTransformOrigin(evt: TouchEvent | MouseEvent) => voidSets the line ripple's transform origin, so that the line ripple activate animation will animate out from the user's click location.
autoCompleteFocus() => voidActivates the Text Field's focus state in cases when the input value is changed programmatically (i.e., without user action).
setAutovalidate(shouldAutovalidate: boolean) => voidSets whether or not the textfield should validate its input when value changes.
getAutovalidate() => booleanWhether or not the textfield should validate its input when value changes. true by default.

MDCTextFieldFoundation supports multiple optional sub-elements: helper text and icon. The foundations of these sub-elements must be passed in as constructor arguments to MDCTextFieldFoundation.

No Web implementation guidance available

Using text fields

Text fields allow users to enter text into a UI. They typically appear in forms and dialogs.

Making text fields accessible

Flutter's text field component APIs supports both label text and helper text for accessibility.

For more guidance on writing labels, go to our page on how to write a good accessibility label.

Types

There are two types of text fields: 1. filled text 2. outlined text

Text field examples, filled and outlined types, showing both inactive and focused states.

Filled text

Filled text fields have more visual emphasis than outlined text fields, making them stand out when surrounded by other content and components.

Filled text example

Source code API:

TextFormField

The following example shows a filled text field.

filled text field with label, helper text, and check circle icon

Anatomy and key properties for filled text

Filled text field anatomy

  1. Container
  2. Leading icon (optional)
  3. Label text
  4. Input text
  5. Trailing icon (optional)
  6. Activation indicator
  7. Helper text (optional)

Container for filled text

 Property
Colorstyle
Stroke colordecoration, inside decoration set the parameter border: disabledBorder, enabledBorder, errorBorder, focusedBorder, focusedErrorBorder
Stroke widthdecoration, inside decoration set the parameter border: disabledBorder, enabledBorder, errorBorder, focusedBorder, focusedErrorBorder
Shapedecoration, inside decoration set the parameter border: disabledBorder, enabledBorder, errorBorder, focusedBorder, focusedErrorBorder
ElevationN/A
Ripple colorN/A

Leading icon (optional) for filled text

 Property
IconUse decoration, within decoration set the icon property
ColorWhen creating the icon property you can set the color parameter
SizeWhen creating the icon property you can set the size parameter
GravityN/A
PaddingN/A

Label text for filled text

 Property
Label textUse decoration, within decoration set labelText property
TypographyUse decoration, within decoration set labelStyle property
ColorUse decoration, within decoration set labelStyle property

Input text for filled text

 Property
Label textinitialValue
Typographystyle
Colorstyle

Trailing icon (optional) for filled text

 Property
IconUse decoration, within decoration use suffixIcon property
ColorWhen creating the suffixIcon property you can set the color parameter
SizeWhen creating the suffixIcon property you can set the size parameter
GravityN/A
PaddingN/A

Activation indicator for filled text

 Property
Stroke colorUse decoration, within decoration set FocusBorder
Stroke widthUse decoration, within decoration set FocusBorder
Ripple colorN/A

Helper text (optional) for filled text

 Property
Label textUse decoration, within decoration set helperText property
TypographyUse decoration, within decoration set helperStyle property
ColorUse decoration, within decoration set helperStyle property

Styles for filled text

 Property
Default stylestyle
Icon styleWithin style set icon

Outlined text

Outlined text fields have less visual emphasis than filled text fields. When they appear in places like forms, where many text fields are placed together, their reduced emphasis helps simplify the layout.

Outlined text example

Source code API:

TextFormField

The following examples shows an outlined text field.

Outlined text field with label, and error message and icon

Anatomy and key properties for outlined text

Outlined text field anatomy

  1. Container
  2. Leading icon (optional)
  3. Label text
  4. Input text
  5. Trailing icon (optional)
  6. Activation indicator
  7. Helper text (optional)

Note: If ThemeData has been declared in the MaterialApp widget it will override the theme that was manually input it like the activation indicator.

Container for outlined text

 Property
Colorstyle
Stroke colordecoration, within decoration set the parameter border: disabledBorder, enabledBorder, errorBorder, focusedBorder, focusedErrorBorder
Stroke widthdecoration, within decoration set the parameter border: disabledBorder, enabledBorder, errorBorder, focusedBorder, focusedErrorBorder
Shapedecoration, within decoration set the parameter border: disabledBorder, enabledBorder, errorBorder, focusedBorder, focusedErrorBorder
ElevationN/A
Ripple colorN/A

Leading icon (optional) for outlined text

 Property
IconUse decoration, within decoration set icon property
ColorWhen creating the icon property set the color parameter
SizeWhen creating the icon property set the size parameter
GravityN/A
PaddingN/A

Label text for outlined text

 Property
Label textUse decoration, within decoration set labelText property
TypographyUse decoration, within decoration set labelStyle property
ColorUse decoration, within decoration set labelStyle property

Input text for outlined text

 Property
Label textinitialValue
Typographystyle
Colorstyle

Trailing icon (optional) for outlined text

 Property
IconUse decoration, within decoration set suffixIcon property
ColorWhen creating the suffixIcon property set the color parameter
SizeWhen creating the suffixIcon property set the size parameter
GravityN/A
PaddingN/A

Activation indicator for outlined text

 Property
Stroke colorUse decoration, within decoration set FocusBorder
Stroke widthUse decoration, within decoration set FocusBorder
Ripple colorN/A

Helper text (optional) for outlined text

 Property
Label textUse decoration, within decoration set helperText property
TypographyUse decoration, within decoration set helperStyle property
ColorUse decoration, within decoration set helperStyle property

Styles for outlined text

 Property
Default stylestyle
Icon styleWithin style set icon

Theming text fields

Text fields support Material Theming and can be customized in terms of color, typography and shape.

Text field theming example

API and source code:

TextFormField

The following example shows a filled text field with the Material Shring Theme.

Shrine filled text field for Flutter

To test code copy and paste code into dartpad.dev

No Flutter implementation guidance available

Using text fields

Installing

To make use of Material text fields, add any of the following subspecs to your Podfile:

Then, run the following command:

From there, import the relevant target or file and instantiate your text field.

Swift

Objective-C

Making text fields accessible

Material iOS text field offerings either inherit from UITextField or they contain UITextView instances. Both of these classes are accessible by default, and generally work out of the box with VoiceOver. However, the text fields we provide make use of floating labels above the text and assistive labels below the text, which makes the VoiceOver behavior of our text fields slightly different. If accessibilityLabel is not explictly set on a single-line text field or multi-line text area, the accessibilityLabel that VoiceOver reads is a concatenation of the floating label text, the entered text, and the assistive label text. If accessibilityLabelis set, the screen reader will read whatever it is set to. If you would like fine-grained control over what VoiceOver reads for these classes it is probably best to set the accessibilityLabel yourself.

Types

There are two types of text fields: 1. filled text fields 2. outlined text fields

"Text field examples of both filled and outlined types, each type showing
both inactive and focused states. The filled text fields show a gray background
and a darker gray activation indicator that is purple when focused. The outlined
text fields show a clear background and an outline that is purple when
focused"

Material iOS text fields consist of both single-line and multi-line offerings in both filled and outlined styles. The single-line text fields are MDCFilledTextField and MDCOutlinedTextField. The multi-line text fields (text areas) are MDCFilledTextArea and MDCOutlinedTextArea. Because these classes make use of things like floating labels and assistive labels, their layout considerations are different than those of UITextField and UITextView. Where UITextField and UITextView can be whatever height a developer wants them to be, these classes have heights that they need to be in order to look correct. The process for ensuring that instances of these classes are sized correctly depends on whether one is in an Auto Layout or Manual Layout environment. In an Auto Layout environment, the text field or text area's preferred height will be reflected in -intrinsicContentSize, and the user will probably not have to do anything other than set a width constraint on the view to ensure that the preferred height is achieved. In a Manual Layout environment, standard methods like -sizeThatFits: or -sizeToFit must be used to inform the frames of the text field. These methods assume that the view already has a preferred width, and that any relevant APIs related to preferred number of lines have been set.

Filled text field

Filled text fields have more visual emphasis than outlined text fields, making them stand out when surrounded by other content and components.

Single-line filled text field

Filled text field

To set up a single-line filled text field using MDCFilledTextField, do the following:

Swift

Objective-C

Multi-line filled text field

Filled text area

To set up a multi-line filled text field (text area) using MDCFilledTextArea, do the following:

Swift

Objective-C

Anatomy and key properties

A filled text field has a filled container, input text, a label, an activation indicator, optional helper/error text and optional leading/trailing icons. This applies to both text fields and text areas.

filled text field anatomy

  1. Container
  2. Leading icon
  3. Label
  4. Input text
  5. Trailing icon
  6. Activation indicator
  7. Helper/error/counter text
  8. Prefix/suffix/placeholder (not supported on iOS)

Container attributes

 AttributeRelated method(s)Default value
ColorN/A-setFilledBackgroundColor:forState:
-filledBackgroundColorForState:
On surface color at 12% opacity

Leading icon attributes

 AttributeRelated method(s)Default value
IconleadingView-setLeadingView
-leadingView
nil

Label attributes

 AttributeRelated method(s)Default value
Textlabel.textN/Anil
Colorlabel.textColor-setFloatingColor:forState:
-floatingLabelColorForState:
-setNormalLabelColor:forState:
-normalLabelColorForState:
On surface color at 60% opacity when not editing and primary color when editing

Input text attributes

 AttributeRelated method(s)Default value
Input texttext-setText:
-text
nil
Typographyfont-setFont:
-font
Subtitle 1
Input text colortextColor-setTextColor:
-textColor
-setTextColor:forState
-textColorForState:
On surface color at 87% opacity
Cursor colortintColor-setTintColor:
-tintColor:
Primary color

Trailing icon attributes

 AttributeRelated method(s)Default value
IcontrailingView-setTrailingView
-trailingView
nil

Activation indicator attributes

 AttributeRelated method(s)Default value
ColorN/A-setUnderlineColor:forState:
-underlineColorForState:
On surface at 42% opacity when not editing and Primary when editing

Helper/error/counter text attributes

 AttributeRelated method(s)Default value
Helper/Error textleadingAssistiveLabel.text
trailingAssistiveLabel.text
N/Anil
Helper/Error text colorleadingAssistiveLabel.textColor
trailingAssistiveLabel.textColor
N/AOn Surface at 60% opacity
Helper text typographyleadingAssistiveLabel.font
trailingAssistiveLabel.font
N/ACaption

Prefix/suffix attributes

Not supported.

Outlined text field

Outlined text fields have less visual emphasis than filled text fields. When they appear in places like forms, where many text fields are placed together, their reduced emphasis helps simplify the layout.

Single-line outlined text field

Outlined text field

To set up a single-line outlined text field using MDCOutlinedTextField, do the following:

Swift

Objective-C

Multi-line Outlined text field

Outlined text area

To set up a multi-line outlined text field (text area) using MDCOutlinedTextArea, do the following:

Swift

Objective-C

Anatomy and key properties

An outlined text field has a stroked container, input text, a label, optional helper/error text and optional leading/trailing icons.

outlined text field anatomy

  1. Container
  2. Leading icon
  3. Label
  4. Input text
  5. Trailing icon
  6. Helper/error/counter text
  7. Prefix/suffix/placeholder (not supported on iOS)

The following examples shows a filled text field with a label.

Container attributes

 AttributeRelated method(s)Default value
Stroke colorN/A-setOutlineColor:forState:
-outlineColorForState:
On surface at 38% opacity when not editing and primary when editing

Leading icon attributes

 AttributeRelated method(s)Default value
IconleadingView-setLeadingView
-leadingView
nil

Label attributes

 AttributeRelated method(s)Default value
Textlabel.textN/Anil
Colorlabel.textColor-setFloatingColor:forState:
-floatingLabelColorForState:
-setNormalLabelColor:forState:
-normalLabelColorForState:
On surface color at 60% opacity when not editing and primary color when editing

Input text attributes

 AttributeRelated method(s)Default value
Input texttext-setText:
-text
nil
Typographyfont-setFont:
-font
Subtitle 1
Input text colortextColor-setTextColor:
-textColor
-setTextColor:forState
-textColorForState:
On surface color at 87% opacity
Cursor colortintColor-setTintColor:
-tintColor:
Primary color

Trailing icon attributes

 AttributeRelated method(s)Default value
IcontrailingView-setTrailingView
-trailingView
nil

Activation indicator attributes

 AttributeRelated method(s)Default value
ColorN/A-setUnderlineColor:forState:
-underlineColorForState:
On surface at 42% opacity when not editing and Primary when editing

Helper/error/counter text attributes

 AttributeRelated method(s)Default value
Helper/Error textleadingAssistiveLabel.text
trailingAssistiveLabel.text
N/Anil
Helper/Error text colorleadingAssistiveLabel.textColor
trailingAssistiveLabel.textColor
N/AOn Surface at 60% opacity
Helper text typographyleadingAssistiveLabel.font
trailingAssistiveLabel.font
N/ACaption

Prefix/suffix attributes

Not supported.

Theming

Text fields and text areas support Material Theming using a Container Scheme. The filled and outlined text fields and text areas each have default theming methods and theming methods intended to convey an error state. Learn more about theming extensions. Below are some screenshots of filled and outlined text fields using the Shrine theme:

Shrine filled text field

Shrine outlined text field

In order to achieve something like the examples shown above, add one of the relevant theming subspecs to your Podfile:

Then Run the installer:

Next, import the relevant target or file.

Swift

Objective-C

From there, call either the default or the error theming method.

Swift

Objective-C

No iOS implementation guidance available

Up next