我想從textview的文本中加粗多個單詞。 我有數組中的文字,我想在textview的文本中加粗。 如何通過SpannableStringBuilder做到這一點?如何在android中編輯textview中的多個單詞
我的數組:
String []數組= { 「生活」, 「幸福」, 「悲傷」, 「眼淚」, 「笑」, 「笑」, 「情感」} ;
我的TextView文本:
生活充滿幸福,悲傷,眼淚,微笑,笑聲和 其他情緒但當生活得到你向下,只要它堅強起來,並保持高昂的頭,並相信生活中的一切。
我經過link和其他,但沒有找到任何我想要的解決方案。
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;
}
@ Myth1c但我想要做動態。通過SpannableStringBuilder – Smily