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

How to make TextInputLayout hint asterisk red for required fields(如何使必填字段的 TextInputLayout 提示星号为红色)

本文介绍了如何使必填字段的 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 提示星号为红色

基础教程推荐