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;
}