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

Categories

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

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


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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...