在使用设计支持库中的 TextInputLayout 时,是否可以只将提示中的星号设为红色?我已经看到有关样式化整个提示的信息,但这有点复杂,因为只有 * 应该是红色的,而不是整个消息。
Material Design 示例显示了这一点,但设计库似乎没有任何选项可以使用 TextInputLayout 和 EditText 以这种方式设置样式。
引用: https://www.google.com/design/spec/components/text-fields.html#text-fields-required-fields
示例(顶部有焦点,有红色星号;没有焦点的底部没有红色星号):
我研究了在 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/