我想从 textview 的文本中加粗多个单词。我在数组中有我想在 textview 的文本中加粗的单词。SpannableStringBuilder 如何做到这一点?
我的数组:
string[] array = {"生活","幸福","悲伤","眼泪","微笑","笑声","情绪"};
我的文本视图文本:
生活充满了幸福、悲伤、泪水、微笑、欢笑和其他情绪,但是当生活让你失望时,只要坚强起来,昂首挺胸,对生活中的一切充满信心。
我通过链接和其他但没有找到我想要的任何解决方案。
TextView text = (TextView) findViewById(R.id.textView1);
String[] list = new String[] { "Life","happiness","sadness","tears","smiles","laughter","emotions"};
String textData ="Life is filled with happiness, sadness, tears, smiles, laughter and other emotions but when life gets you down, just be strong about it and keep your head up high and have faith in all things in life";
CharSequence cseq = "";
for(int i = 0 ; i < list.length ; i++)
{
cseq = setSpanBetweenTokens(textData, list[i] , new StyleSpan(Typeface.BOLD_ITALIC));
}
text.setText(cseq.toString());
public static CharSequence setSpanBetweenTokens(CharSequence text,
String token, CharacterStyle... cs)
{
// Start and end refer to the points where the span will apply
int tokenLen = token.length();
int start = text.toString().indexOf(token) + tokenLen;
int end = text.toString().indexOf(token, start);
if (start > -1 && end > -1)
{
// Copy the spannable string to a mutable spannable string
SpannableStringBuilder ssb = new SpannableStringBuilder(text);
for (CharacterStyle c : cs)
ssb.setSpan(c, start, end, 0);
// Delete the tokens before and after the span
ssb.delete(end, end + tokenLen);
ssb.delete(start - tokenLen, start);
text = ssb;
}
return text;
}