android - 如何使必填字段的 TextInputLayout 提示星号为红色

标签 android android-edittext material-design android-textinputlayout

在使用设计支持库中的 TextInputLayout 时,是否可以只将提示中的星号设为红色?我已经看到有关样式化整个提示的信息,但这有点复杂,因为只有 * 应该是红色的,而不是整个消息。

Material Design 示例显示了这一点,但设计库似乎没有任何选项可以使用 TextInputLayout 和 EditText 以这种方式设置样式。

引用: https://www.google.com/design/spec/components/text-fields.html#text-fields-required-fields

示例(顶部有焦点,有红色星号;没有焦点的底部没有红色星号):

Example of hint text with red asterisk

我研究了在 OnFocusChangeListener(参见此处 How to get a red asterisk in a <string> entry)中将提示设置为 SpannableString(参见此处 Having the mandatory symbol to the edit text (red color asterisk) which is inside the textinputlayout),但提示是 CharSequence。

有什么方法可以在不扩展 TextInputLayout 的情况下做到这一点?

最佳答案

Material Design 为作为提示文本一部分的必填字段指定一个星号,并且颜色相同(不像您在问题中显示的那样为红色)。

在 Kotlin 中这非常简单:

1.定义这个扩展方法:

fun TextInputLayout.markRequired() {
    hint = "$hint *"
}

2.使用它:

input_first_name.markRequired()

如果您仍然想要星号红色,尽管 Material Design 指南不鼓励您,您可以这样使用 AndroidX Core KTX:

fun TextInputLayout.markRequiredInRed() {
    hint = buildSpannedString {
        append(hint)
        color(Color.RED) { append(" *") } // Mind the space prefix.
    }
}

关于android - 如何使必填字段的 TextInputLayout 提示星号为红色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35798166/

相关文章:

android - 安排 AsyncTask 每分钟运行一次

android - 将常量文本放在应该不可编辑的 EditText 中 - Android

php - 如何在Yii2中添加物化

android - Android EditText 的圆角边框

android - 使用EditText完成后是否更新数据库中的值?

Android:设置编辑文本字段物理长度的方法

安卓 Material : Status bar color won't change

android - 如果特定日期值不存在,则获取以前的条目

android - 在 Android Studio 中的每个预览中都会显示闪屏主题

android - 使用 Mockito 模拟改造服务导致 ExceptionInInitializerError