問題描述
在使用設(shè)計支持庫中的 TextInputLayout 時,是否可以只將提示中的星號設(shè)為紅色?我已經(jīng)看到有關(guān)樣式化整個提示的信息,但這有點復(fù)雜,因為只有 * 應(yīng)該是紅色的,而不是整個消息.
Material Design 示例顯示了這一點,但設(shè)計庫似乎沒有任何選項可以使用 TextInputLayout 和 EditText 以這種方式設(shè)置樣式.
參考:
我研究了將提示設(shè)置為 SpannableString(請參閱此處 如何在 OnFocusChangeListener 中的 <string> entry 中獲取紅色星號(請參見此處 對文本輸入布局內(nèi)的編輯文本(紅色星號)具有強制符號),但提示是一個字符序列.
有什么方法可以在不擴(kuò)展 TextInputLayout 的情況下做到這一點?
Material Design 為作為提示文本一部分的必填字段指定一個星號,并且顏色相同(不像您在問題中顯示的那樣為紅色).
在 Kotlin 中這非常簡單:
1.定義這個擴(kuò)展方法:
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.
}
}
這篇關(guān)于如何使必填字段的 TextInputLayout 提示星號為紅色的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!