Android Material Design 系列之 TextInputLayout 使用详解

本文详述了Android中的TextInputLayout组件,作为EditText的容器,实现浮动标签和丰富的交互功能,包括错误提示、自定义样式、密码切换及输入校验。通过XML属性和API,轻松实现Material Design的优雅动画效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

本文是 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
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值