前言
本文是 Material Design 系列第四篇:TextInputLayout 主要是作为 EditText 的容器,从而为 EditText 生成一个浮动的 Label,当用户点击 EditText 的时候,EditText 中的 hint 字符串会自动移到 EditText 的左上角。
TextInputLayout 的简单使用,是 Google 推出的整个 Material Design 库的一个缩影:Google 将 UI 视觉效果设计得华丽且流畅,同时代码封装更为优雅,开发者只需要在 layout.xml 中写好布局文件,就可以轻松在手机屏幕上展现出魔法般的动画效果,实在是妙不可言。
一、TextInputLayout 相关 API
TextInputLayout 控件 API 官网列举了很多,这里只是整理出开发中常用属性,每个方法对应相关 XML 属性感兴趣的可以查查官网文档。
方法 | 介绍 |
---|---|
setCounterEnabled(boolean enabled) | 在此布局中是否启用了字符计数器功能。 |
setCounterMaxLength(int maxLength) | 设置要在字符计数器上显示的最大长度。 |
setBoxBackgroundColorResource(int boxBackgroundColorId) | 设置用于填充框的背景色的资源。 |
setBoxStrokeColor(int boxStrokeColor) | 设置轮廓框的笔触颜色。 |
setCounterOverflowTextAppearance(int counterOverflowTextAppearance) | 使用指定的 TextAppearance 资源设置溢出字符计数器的文本颜色和大小。 |
setCounterOverflowTextColor(ColorStateList counterOverflowTextColor) | 使用 ColorStateList 设置溢出字符计数器的文本颜色。(此文本颜色优先于 counterOverflowTextAppearance 中设置的文本颜色) |
setCounterTextAppearance(int counterTextAppearance) | 使用指定的 TextAppearance 资源设置字符计数器的文本颜色和大小。 |
setCounterTextColor(ColorStateList counterTextColor) | 使用 ColorStateList 设置字符计数器的文本颜色。(此文本颜色优先于 counterTextAppearance 中设置的文本颜色) |
setErrorEnabled(boolean enabled) | 在此布局中是否启用了错误功能。 |
setErrorTextAppearance(int errorTextAppearance) | 设置来自指定 TextAppearance 资源的错误消息的文本颜色和大小。 |
setErrorTextColor(ColorStateList errorTextColor) | 设置错误消息在所有状态下使用的文本颜色。 |
setHelperText(CharSequence helperText) | 设置将在下方显示的帮助消息 EditText。 |
setHelperTextColor(ColorStateList helperTextColor) | 设置辅助状态在所有状态下使用的文本颜色。 |
setHelperTextEnabled(boolean enabled) | 在此布局中是否启用了辅助文本功能。 |
setHelperTextTextAppearance(int helperTextTextAppearance) | 设置指定 TextAppearance 资源中的辅助文本的文本颜色和大小。 |
setHint(CharSequence hint) | 设置要在浮动标签中显示的提示(如果启用)。 |
setHintAnimationEnabled(boolean enabled) | 是否获取焦点的时候,hint 文本上移到左上角开启动画。 |
setHintEnabled(boolean enabled) | 设置是否在此布局中启用浮动标签功能。 |
setHintTextAppearance(int resId) | 从指定的 TextAppearance 资源设置折叠的提示文本的颜色,大小,样式。 |
setHintTextColor(ColorStateList hintTextColor) | 从指定的 ColorStateList 资源设置折叠的提示文本颜色。 |
setPasswordVisibilityToggleEnabled(boolean enabled) | 启用或禁用密码可见性切换功能。 |
二、TextInputLayout 使用详解
1、基本使用
- 布局文件中只需要在 EditText 外层包裹一层 TextInputLayout 布局即可
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/userInputLayout"
android:layout_width="match_parent"
android:layout_height