Android中TextInputLayout/TextInputEditText样式设置完整方案分享
TextInputLayout/TextInputEditText 适配新版Android的样式设置方案
我在开发中需要使用TextInputLayout和TextInputEditText控件,查找样式设置方法时发现很多旧资料因为Android版本迭代已经不再适配,现有资料也没能给出完整解决方案,所以整理了一套适配新版的实现方案分享出来。
一、基础样式配置(Material Design 3 适配)
如果项目使用Material Design 3,建议通过Theme属性全局配置,或单独给控件设置style:
- 全局主题配置
在res/values/styles.xml中修改App主题:
<style name="Theme.MyApp" parent="Theme.Material3.DayNight.NoActionBar"> <!-- 全局TextInputLayout样式 --> <item name="textInputStyle">@style/Widget.MyApp.TextInputLayout</item> </style> <style name="Widget.MyApp.TextInputLayout" parent="Widget.Material3.TextInputLayout.FilledBox"> <!-- 基础属性配置 --> <item name="hintTextColor">@color/primary</item> <item name="boxStrokeColor">@color/primary</item> <item name="boxBackgroundColor">@color/surface_variant</item> <item name="errorIconTint">@color/error</item> </style>
- 单个控件单独设置
布局文件中直接指定style:
<com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" style="@style/Widget.MyApp.TextInputLayout" android:hint="用户名"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text"/> </com.google.android.material.textfield.TextInputLayout>
二、自定义选中/未选中状态的颜色
如果需要更精细的状态控制,可使用selector:
创建res/color/text_input_box_stroke_color.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@color/primary" android:state_focused="true"/> <item android:color="@color/outline" android:state_hovered="true"/> <item android:color="@color/outline_variant"/> </selector>
然后在TextInputLayout的style中引用:
<item name="boxStrokeColor">@color/text_input_box_stroke_color</item>
三、自定义字体与文字样式
给TextInputEditText设置自定义字体,同时调整提示文字大小:
<style name="Widget.MyApp.TextInputEditText" parent="Widget.Material3.TextInputEditText.FilledBox"> <item name="android:fontFamily">@font/custom_font</item> <item name="android:textSize">16sp</item> <item name="hintTextSize">14sp</item> </style>
在布局中给TextInputEditText指定该style:
<com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" style="@style/Widget.MyApp.TextInputEditText" android:inputType="text"/>
四、错误提示样式自定义
调整错误提示的文字颜色、位置和图标:
<style name="Widget.MyApp.TextInputLayout" parent="Widget.Material3.TextInputLayout.FilledBox"> <item name="errorTextColor">@color/error</item> <item name="errorIconDrawable">@drawable/ic_custom_error</item> <item name="errorEnabled">true</item> </style>
代码中设置错误信息:
textInputLayout.error = "输入格式不正确"
感谢Dmytro发布的博客内容,为这套实现方案提供了重要参考。
内容的提问来源于stack exchange,提问作者Michel
相关产品推荐
相关产品推荐

