I have defined TextInputLayout programmatically in my Activity. I have added EditText inside that TextInputLayout, that to programmatically.
Now, I have to set the color of hint of that edittext. Here I just have to change the color of single alphabet of the hint.
Example - Hint is like, Firstname *. Here i want to change the color of "*" to Red and remaining hint as black in color.
I have already tried Html and Spannable String, but both are not working for TextInputLayout.
For Spannable i did
SpannableString redSpannable = new SpannableString(red);
redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, red.length(), 0);
Spanned hint = Html.fromHtml(string + redSpannable);
etDefault[j].setHint(hint);
For HTML,
I used "font-color"
If anyone knows this, then share your opinion.
As per the Android Issue Tracker,
Setting the hint to the editText respects the span, but the label does not float on focus.
editText.setHint(hint);
Setting the hint to the textInputLayout ignores the span
textInputLayout.setHint(hint);
TextInputLayout uses internal class CollapsingTextHelper to draw the hint, which does not support spans.
And as they said,
They have passed this defect on to the development team and will update this issue with more information as it becomes available.
I suggest you using just SpannableStringBuilder
without Html.fromHtml
:
SpannableStringBuilder sb = new SpannableStringBuilder("Hint with first letter black");
CharacterStyle cs= new ForegroundColorSpan(ContextCompat.getColor(this, android.R.color.black));
sb.setSpan(cs, 0, 1, 0);
((TextView) findViewById(R.id.description_messages)).setHint(sb);
In this piece of code the first letter becomes black. If you would like it to be bold too, use this:
CharacterStyle cs = new StyleSpan(android.graphics.Typeface.BOLD);
That just puts hint to EditText
. There will be no floating text effect.
In TextInputLayout change the color of hint for single letter or alphabet
String firstNameText ="firstName *";
Spanned redStar;
String html = "<string style="color:firstNameText;">firstName<span style="color:red;">*</span></string>";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.L) {
redStar = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
} else { redStar = Html.fromHtml(html); }
来源:https://stackoverflow.com/questions/39656596/in-textinputlayout-change-the-color-of-hint-for-single-letter-or-alphabet