简体   繁体   English

如何在 Android Material TextInputLayout 中将 SpannableString 设置为 EditText?

[英]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.我找不到将 Material TextInputLayoutEditText的文本设置为SpannableString并让样式实际显示在屏幕上的方法。 I've tried every combination of EditText inside a TextInputLayout , eg:我已经尝试了TextInputLayoutEditText的每种组合,例如:

  1. AppCompatEditText
  2. EditText
  3. TextInputEditText

with every way to create a SpannableString , eg:以各种方式创建SpannableString ,例如:

  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 , eg:以各种方式设置EditText的文本,例如:

  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.疯狂的是,当 EditText 不在 Material TextInputLayout中时,它们都可以工作,所以这一定是个问题。 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.更多信息:当您在TextInputLayout上设置提示或占位符文本时,会尊重SpannableString ,而不是其中的EditText的文本。 I looked through the TextInputLayout source code, but didn't see anything wrong.我查看了TextInputLayout源代码,但没有发现任何错误。 Thanks to anyone who can help.感谢任何能提供帮助的人。

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.您可以从EditText获取Editable的 object,然后将Span应用于它。 Here's how:就是这样:

mEditText.text.setSpan(...)

Surprisingly easy when you know where to look.当您知道在哪里寻找时,这非常容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM