TextInputLayout
Макет TextInputLayout сначала появился в библиотеке Android Design Support Library и добавляет немного красоты к текстовому полю. Когда пользователь начинает вводить текст в текстовом поле, то подсказка, заданная в этом компоненте, всплывает над ним в специальном TextView. Пример можно увидеть на видео.
Библиотека больше не развивается, поэтому используйте AndroidX, которую я и буду теперь использовать в описании.
Компонент можно найти на панели инструментов в разделе Text.
При добавлении компонента через визуальный редактор автоматически добавляется дочерний элемент TextInputEditText.
Так выглядел компонент в составе Support Library.
Подсказку не обязательно указывать в атрибуте android:hint у текстового поля. Можно программно присвоить через метод:
Стилизация
В AndroidX у компонента появились новые стили: OutlinedBox, FilledBox. Можете самостоятельно запустить пример с двумя стилями и посмотреть на отличия.
Далее идёт текст для старой версии статьи. Вам следует самостоятельно обновить нужные фрагменты кода.
Общая стилизация доступна следующим образом. Пропишем стили в styles.xml:
Обработка ошибки
Предыдущий пример показывал применение подсказки. Но также можно выводить сообщения об ошибке. Здесь потребуется написать немного кода. За вывод ошибки отвечает атрибут app:errorEnabled. Назначим текстовому полю тип клавиатуры и однострочный текст. При наборе текста после нажатия на клавишу Enter проверяем длину текста. Если текст меньше четырёх символов, то выводим сообщение об ошибке.
Текст ошибки выводится снизу от текстового поля.
Стиль для сообщения об ошибке можно стилизовать. Добавим новый атрибут.
В файле стилей res/values/styles.xml добавим новый стиль:
Теперь выводится другим цветом.
Расширенный вид стилей:
Применяем через атрибуты app:errorTextAppearance и android:theme.
Счётчик символов
С помощью атрибутов app:counterEnabled и app:counterMaxLength можно установить счётчик символов с указанием предела, который будет выводиться под текстовым полем.
Когда будет превышен лимит, то цвет счётчика изменится. Этот цвет можно стилизовать через стиль.
Стиль применяется к атрибуту app:counterOverflowTextAppearance:
TextInputEditText
Казалось бы простой компонент, никаких трудностей не возникает. Но не торопитесь. Стоит повернуть устройства в альбомный режим, как текстовое поле растянется на весь экран и никакой подсказки вы не увидите. Возможно, это баг, который когда-нибудь починят. Но проблему легко решить, если вместо стандартного EditText использовать специальный компонент из библиотеки TextInputEditText:
Источник
Android textinputedittext clear button
Text fields let users enter and edit text.
Contents
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, which explain what is requested for a text field. While optional, their use is strongly encouraged.
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.
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 the error will announce the content description instead of the error message.
Note: Icons that don’t have click listeners set on them work as decorative elements, and are therefore skipped by screen readers.
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
Adding a trailing icon to a text field
Password toggle:
When the TextInputEditText is set to display a password, an icon can be added to toggle between masking the password or displaying the password as plain-text.
Clear text:
An icon can be set to display when text is present. The icon can be pressed to clear the input text.
Custom 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 you have the option to specify custom behaviors.
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
In the item layout ( list_item.xml ):
Adding helper text to a text field
Adding a counter to a text field
Adding errors to a text field
Note: Non-null error text will replace any existing helper text, and non-null helper text will replace any existing error text.
Adding a prefix/suffix to a text field
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 by making changes 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.
There are two types of text fields: 1. Filled text field, 2. Outlined text field
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.
Filled text field examples
API and source code:
The following example shows a filled text field with a label.
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.
- Container
- Leading icon
- Label
- Input text
- Trailing icon
- Activation indicator
- Helper/error/counter text
- Prefix/suffix/placeholder (not shown)
Note: All the attributes in the tables below should be set on the TextInputLayout , with the exception of the input text attributes, which should be set on the TextInputEditText .
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Color | app:boxBackgroundColor | setBoxBackgroundColor setBoxBackgroundColorResource getBoxBackgroundColor | ?attr/colorSurfaceVariant (see all states) |
Shape | app:shapeAppearance | N/A | ?attr/shapeAppearanceSmallComponent |
Text field enabled | android:enabled | setEnabled | true |
Leading icon attributes
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Icon | app:startIconDrawable | setStartIconDrawable getStartIconDrawable | null |
Content description | app:startIconContentDescription | setStartIconContentDescription getStartIconContentDescription | null |
Color | app:startIconTint | setStartIconTintList | ?attr/colorOnSurfaceVariant (see all states) |
Checkable | app:startIconCheckable | setStartIconCheckable isStartIconCheckable | false |
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Text | android:hint | setHint getHint | null |
Color | android:textColorHint | setDefaultHintTextColor getDefaultHintTextColor | ?attr/colorOnSurfaceVariant (see all states) |
Collapsed (floating) color | app:hintTextColor | setHintTextColor getHintTextColor | ?attr/colorPrimary (see all states) |
Typography | app:hintTextAppearance | setHintTextAppearance | ?attr/textAppearanceBodySmall |
Animation | app:hintAnimationEnabled | setHintAnimationEnabled isHintAnimationEnabled | true |
Expanded enabled | app:expandedHintEnabled | setExpandedHintEnabled 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
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Input text | android:text | setText getText | @null |
Typography | android:textAppearance | setTextAppearance | ?attr/textAppearanceBodyLarge |
Input text color | android:textColor | setTextColor getTextColors getCurrentTextColor | ?attr/colorOnSurface |
Cursor color | N/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
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Mode | app:endIconMode | setEndIconMode getEndIconMode | END_ICON_NONE |
Color | app:endIconTint | setEndIconTintList | colorOnSurfaceVariant (see all states) |
Custom icon | app:endIconDrawable | setEndIconDrawable getEndIconDrawable | null |
Custom icon content description | app:endIconContentDescription | setEndIconContentDescription getEndIconContentDescription | null |
Custom icon checkable | app:endIconCheckable | setEndIconCheckable isEndIconCheckable | true |
Error icon | app:errorIconDrawable | setErrorIconDrawable getErrorIconDrawable | @drawable/mtrl_ic_error |
Error icon color | app:errorIconTint | setErrorIconTintList | ?attr/colorError |
Activation indicator attributes
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Color | app:boxStrokeColor | setBoxStrokeColor setBoxStrokeColorStateList getBoxStrokeColor | ?attr/colorOutline and ?attr/colorPrimary (focused) (see all states) |
Error color | app:boxStrokeErrorColor | setBoxStrokeErrorColor getBoxStrokeErrorColor | ?attr/colorError |
Width | app:boxStrokeWidth | N/A | 1dp |
Focused width | app:boxStrokeWidthFocused | N/A | 2dp |
Helper/error/counter text attributes
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Helper text enabled | app:helperTextEnabled | setHelperTextEnabled isHelperTextEnabled | false |
Helper text | app:helperText | setHelperText getHelperText | null |
Helper text color | app:helperTextColor | setHelperTextColor getHelperTextColor | ?attr/colorOnSurfaceVariant (see all states) |
Helper text typography | app:helperTextAppearance | setHelperTextAppearance | ?attr/textAppearanceBodySmall |
Error text enabled | app:errorEnabled | setErrorEnabled isErrorEnabled | false |
Error text | N/A | setError getError | null |
Error text color | app:errorTextColor | setErrorTextColor getErrorCurrentTextColors | ?attr/colorError |
Error text typography | app:errorTextAppearance | setErrorTextAppearance | ?attr/textAppearanceBodySmall |
Counter text enabled | app:counterEnabled | setCounterEnabled isCounterEnabled | false |
Counter text length | app:counterMaxLength | setCounterMaxLength getCounterMaxLength | -1 |
Counter text typography | app:counterTextAppearance app:counterOverflowTextAppearance | setCounterTextAppearance setCounterOverflowTextAppearance | ?attr/textAppearanceBodySmall |
Counter text color | app:counterTextColor app:counterOverflowTextColor | setCounterTextColor setCounterOverflowTextColor getCounterTextColor getCounterOverflowTextColor | ?attr/colorOnSurfaceVariant ( app:counterTextColor ) (see all states) ?attr/colorError ( app:counterOverflowTextColor ) |
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Prefix | app:prefixText | setPrefixText getPrefixText | null |
Prefix color | app:prefixTextColor | setPrefixTextColor getPrefixTextColor | ?attr/colorOnSurfaceVariant (see all states) |
Prefix typography | app:prefixTextAppearance | setPrefixTextAppearance | ?attr/textAppearanceTitleMedium |
Suffix | app:suffixText | setSuffixText getSuffixText | null |
Suffix color | app:suffixTextColor | setSuffixTextColor getSuffixTextColor | ?attr/colorOnSurfaceVariant (see all states) |
Suffix typography | app:suffixTextAppearance | setSuffixTextAppearance | ?attr/textAppearanceTitleMedium |
Element | Style | Default style theme attribute |
---|---|---|
Default style | Widget.Material3.TextInputLayout.FilledBox | ?attr/textInputFilledStyle |
Dense style | Widget.Material3.TextInputLayout.FilledBox.Dense | ?attr/textInputFilledDenseStyle |
Exposed dropdown menu style | Widget.Material3.TextInputLayout.FilledBox.ExposedDropdownMenu | ?attr/textInputFilledExposedDropdownMenuStyle |
Dense exposed dropdown menu style | Widget.Material3.TextInputLayout.FilledBox.Dense.ExposedDropdownMenu | N/A |
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 forms, for example, where many text fields are placed together, their reduced emphasis helps simplify the layout.
Note: The outlined text field is the default style.
Outlined text field examples
API and source code:
The following example shows an outlined text field.
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.
- Container
- Leading icon
- Label
- Input text
- Trailing icon
- Helper/error/counter text
- Prefix/suffix/placeholder (not shown)
Note: All the attributes in the tables below should be set on the TextInputLayout , with the exception of the input text attributes, which should be set on the TextInputEditText .
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Stroke color | app:boxStrokeColor | setBoxStrokeColor setBoxStrokeColorStateList getBoxStrokeColor | ?attr/colorOutline and ?attr/colorPrimary (focused) (see all states) |
Stroke error color | app:boxStrokeErrorColor | setBoxStrokeErrorColor getBoxStrokeErrorColor | ?attr/colorError |
Stroke width | app:boxStrokeWidth | N/A | 1dp |
Stroke focused width | app:boxStrokeWidthFocused | N/A | 2dp |
Shape | app:shapeAppearance | N/A | ?attr/shapeAppearanceSmallComponent |
Text field enabled | android:enabled | setEnabled | true |
Leading icon attributes
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Icon | app:startIconDrawable | setStartIconDrawable getStartIconDrawable | null |
Content description | app:startIconContentDescription | setStartIconContentDescription getStartIconContentDescription | null |
Color | app:startIconTint | setStartIconTintList | ?attr/colorOnSurfaceVariant (see all states) |
Checkable | app:startIconCheckable | setStartIconCheckable isStartIconCheckable | false |
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Text | android:hint | setHint getHint | null |
Color | android:textColorHint | setDefaultHintTextColor getDefaultHintTextColor | ?attr/colorOnSurfaceVariant (see all states) |
Collapsed (floating) color | app:hintTextColor | setHintTextColor getHintTextColor | ?attr/colorPrimary |
Typography | app:hintTextAppearance | setHintTextAppearance | ?attr/textAppearanceBodySmall |
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
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Input text | android:text | setText getText | @null |
Typography | android:textAppearance | setTextAppearance | ?attr/textAppearanceBodyLarge |
Input text color | android:textColor | setTextColor getTextColors getCurrentTextColor | ?attr/colorOnSurface |
Cursor color | N/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
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Mode | app:endIconMode | setEndIconMode getEndIconMode | END_ICON_NONE |
Color | app:endIconTint | setEndIconTintList | ?attr/colorOnSurfaceVariant (see all states) |
Custom icon | app:endIconDrawable | setEndIconDrawable getEndIconDrawable | null |
Custom icon content description | app:endIconContentDescription | setEndIconContentDescription getEndIconContentDescription | null |
Custom icon checkable | app:endIconCheckable | setEndIconCheckable isEndIconCheckable | true |
Error icon | app:errorIconDrawable | setErrorIconDrawable getErrorIconDrawable | @drawable/mtrl_ic_error |
Error icon color | app:errorIconTint | setErrorIconTintList | ?attr/colorError |
Helper/error/counter text attributes
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Helper text enabled | app:helperTextEnabled | setHelperTextEnabled isHelperTextEnabled | false |
Helper text | app:helperText | setHelperText getHelperText | null |
Helper text color | app:helperTextColor | setHelperTextColor getHelperTextColor | ?attr/colorOnSurfaceVariant (see all states) |
Helper text typography | app:helperTextAppearance | setHelperTextAppearance | ?attr/textAppearanceBodySmall |
Error text enabled | app:errorEnabled | setErrorEnabled isErrorEnabled | false |
Error text | N/A | setError getError | null |
Error text color | app:errorTextColor | setErrorTextColor getErrorCurrentTextColors | ?attr/colorError |
Error text typography | app:errorTextAppearance | setErrorTextAppearance | ?attr/textAppearanceBodySmall |
Counter text enabled | app:counterEnabled | setCounterEnabled isCounterEnabled | false |
Counter text length | app:counterMaxLength | setCounterMaxLength getCounterMaxLength | -1 |
Counter text typography | app:counterTextAppearance app:counterOverflowTextAppearance | setCounterTextAppearance setCounterOverflowTextAppearance | ?attr/textAppearanceBodySmall |
Counter text color | app:counterTextColor app:counterOverflowTextColor | setCounterTextColor setCounterOverflowTextColor getCounterTextColor getCounterOverflowTextColor | ?attr/colorOnSurfaceVariant ( app:counterTextColor ) (see all states) ?attr/colorError ( app:counterOverflowTextColor ) |
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Prefix | app:prefixText | setPrefixText getPrefixText | null |
Prefix color | app:prefixTextColor | setPrefixTextColor getPrefixTextColor | ?attr/colorOnSurfaceVariant (see all states) |
Prefix typography | app:prefixTextAppearance | setPrefixTextAppearance | ?attr/textAppearanceTitleMedium |
Suffix | app:suffixText | setSuffixText getSuffixText | null |
Suffix color | app:suffixTextColor | setSuffixTextColor getSuffixTextColor | ?attr/colorOnSurfaceVariant (see all states) |
Suffix typography | app:suffixTextAppearance | setSuffixTextAppearance | ?attr/textAppearanceTitleMedium |
Element | Style | Default style theme attribute |
---|---|---|
Default style | Widget.Material3.TextInputLayout.OutlinedBox | ?attr/textInputStyle and ?attr/textInputOutlinedStyle |
Dense style | Widget.Material3.TextInputLayout.OutlinedBox.Dense | ?attr/textInputOutlinedDenseStyle |
Exposed dropdown menu style | Widget.Material3.TextInputLayout.OutlinedBox.ExposedDropdownMenu | ?attr/textInputOutlinedExposedDropdownMenuStyle |
Dense exposed dropdown menu style | Widget.Material3.TextInputLayout.OutlinedBox.Dense.ExposedDropdownMenu | N/A |
See the full list of styles and attrs.
Theming text fields
Text fields support Material Theming which provides color, typography and shape customization.
Text field theming example
API and source code:
The following example shows filled and outlined text field types with Material Theming.
Implementing text field theming
Using theme attributes and styles in res/values/styles.xml adds themes to all text fields and affects other components:
Using default style theme attributes, styles and theme overlays adds themes to all text fields but does not affect other components:
Using the style in the layout affects only this text field:
Источник