我有一个句子中的特定单词列表,我想加粗并更改文本颜色。出于某种原因,文本颜色更改正在起作用,但似乎没有应用粗体。更奇怪的是,将字体更改为斜体会反映出来。我的问题是,什么可能导致我的文字不加粗?
// 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