可以将多个setSpan应用于同一SpannableStringBuilder吗?

时间:2018-10-24 19:17:39

标签: android android-typeface spannablestringbuilder

我有一个句子中的特定单词的列表,我想将其加粗并更改其文本颜色。出于某种原因,文本颜色更改可以正常工作,但似乎没有应用粗体。更奇怪的是,将字体更改为斜体会反映出来。我的问题是,是什么导致我的文字不加粗?

// lets create a list of words
ArrayList<String> alWords = new ArrayList<>();
alWords.add("Mary");
alWords.add("lamb");

// had earlier StringBuilder to form 'Mary had a little lamb.' for example
SpannableStringBuilder sentence = new SpannableStringBuilder(sb.toString());

// iterate through list of words and bold & color change text
for (int i = 0; i < alWords.size(); i++) {
   Pattern word = Pattern.compile(alWords.get(i));
   Matcher match = word.matcher(sentence);

   int startPos = 0;
   int endPos = 0;

   while (match.find()) {
      startPos = match.start();
      endPos = match.end();
   }
   sentence.setSpan(new StyleSpan(Typeface.BOLD), startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
   sentence.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.green)), startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} 

tvText.setText(sentence, TextView.BufferType.SPANNABLE);

这会导致正确的词出现颜色变化,但不会出现粗体。如果您将其更新为斜体,那么它也可以使用。仅粗体文本无效。有什么想法吗?

为了进一步检查,这是我的dumpSpans日志:

span= Mary: 1c181a6 android.text.style.StyleSpan (0-4) fl=#33 
span= Mary: 148f7e7 android.text.style.ForegroundColorSpan (0-4) fl=#33 
span= lamb: b441f94 android.text.style.StyleSpan (18-22) fl=#33 
span= lamb: e18ba3d android.text.style.ForegroundColorSpan (18-22) fl=#33

1 个答案:

答案 0 :(得分:1)

我使用SpannableStringBuilder而不是SpannableString,它工作正常。
尝试使用以下代码:

SpannableString sentence = new SpannableString(sb.toString());

然后

tvText.setText(sentence);