javaandroidkotlinandroid-edittextmaterial-components-android

How to set a SpannableString to an EditText in an Android Material TextInputLayout?


I can't find a way to set the text of an EditText in a Material TextInputLayout to a SpannableString and have the styling actually show up on screen. I've tried every combination of EditText inside a TextInputLayout, e.g.:

  1. AppCompatEditText
  2. EditText
  3. TextInputEditText

with every way to create a SpannableString, e.g.:

  1. HtmlCompat.fromHtml(string, HtmlCompat.FROM_HTML_MODE_COMPACT)
  2. SpannableString(string).setSpan(...)
  3. TextUtils.stringOrSpannedString(string)

with every way to set the text of an EditText, e.g.:

  1. edittext.setText(spannedString)
  2. edittext.setText(spannedString, TextView.BufferType.SPANNABLE)
  3. edittext.append(spannedString)

The crazy thing is they all work when the EditText is not inside a Material TextInputLayout, so it must be a problem with that. More information: the SpannableString is respected when you set the hint or placeholder text on the TextInputLayout, just not the text of the EditText inside it. I looked through the TextInputLayout source code, but didn't see anything wrong. Thanks to anyone who can help.


Solution

  • I figured it out right when I was going to give up. You can get the Editable object from the EditText and then apply the Span to it. Here's how:

    mEditText.text.setSpan(...)
    

    Surprisingly easy when you know where to look.