How to make TextInputLayout hint asterisk red for required fields(如何使必填字段的 TextInputLayout 提示星号为红色)
问题描述
在使用设计支持库中的 TextInputLayout 时,是否可以只将提示中的星号设为红色?我已经看到有关样式化整个提示的信息,但这有点复杂,因为只有 * 应该是红色的,而不是整个消息.
Material Design 示例显示了这一点,但设计库似乎没有任何选项可以使用 TextInputLayout 和 EditText 以这种方式设置样式.
参考:
我研究了将提示设置为 SpannableString(请参阅此处 如何在 OnFocusChangeListener 中的 <string> entry 中获取红色星号(请参见此处 对文本输入布局内的编辑文本(红色星号)具有强制符号),但提示是一个字符序列.
有什么方法可以在不扩展 TextInputLayout 的情况下做到这一点?
Material Design 为作为提示文本一部分的必填字段指定一个星号,并且颜色相同(不像您在问题中显示的那样为红色).
在 Kotlin 中这非常简单:
1.定义这个扩展方法:
fun TextInputLayout.markRequired() {提示 = "$提示 *"}
2.使用它:
input_first_name.markRequired()
如果您仍然想要星号红色,尽管 Material Design 指南不鼓励您,您可以这样使用 AndroidX Core KTX:
fun TextInputLayout.markRequiredInRed() {提示 = buildSpannedString {附加(提示)color(Color.RED) { append(" *") }//注意空格前缀.}}
Is it possible to make just the asterisk in the hint red when using a TextInputLayout from the design support library? I have seen information on styling the entire hint, but this is a little more complex since only the * should be red, not the whole message.
The Material Design example shows this, but the design library doesn't seem to have any option to style it this way using a TextInputLayout and EditText.
Reference: https://www.google.com/design/spec/components/text-fields.html#text-fields-required-fields
Example (the top, with focus, has the red asterisk; the bottom without focus does not have a red asterisk):
I looked into setting the hint to a SpannableString (see here How to get a red asterisk in a <string> entry) in an OnFocusChangeListener (see here Having the mandatory symbol to the edit text (red color asterisk) which is inside the textinputlayout), but the hint is a CharSequence.
Is there any way to do this without extending TextInputLayout?
Material Design specify an asterisk for the required fields that is part of the hint text, and of the same color (not in red like you showed in your question).
In Kotlin this is really simple:
1.Define this extension method:
fun TextInputLayout.markRequired() {
hint = "$hint *"
}
2.Use it:
input_first_name.markRequired()
If you still want the asterisk red, despite being discouraged by Material Design guidelines, you can use AndroidX Core KTX that way:
fun TextInputLayout.markRequiredInRed() {
hint = buildSpannedString {
append(hint)
color(Color.RED) { append(" *") } // Mind the space prefix.
}
}
这篇关于如何使必填字段的 TextInputLayout 提示星号为红色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使必填字段的 TextInputLayout 提示星号为红色
基础教程推荐
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01