Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

android - How to make TextInputLayout hint asterisk red for required fields

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):

Example of hint text with 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...