在我的Android应用程序中,我有一个包含特定单词的字符串,所以我想在文本视图中显示整个字符串,并且应该突出显示特定的单词.希望下面的图像会给你一个想法.

我使用以下代码来执行此操作但它不起作用.
码:
con是我的字符串,groupNameContent是文本字段.
con.replaceAll(arrGroupelements[groupPosition][5],"<font color='#CA278C'>"+arrGroupelements[groupPosition][5]+"</font>.");
groupNameContent.setText(Html.fromHtml(con));
Run Code Online (Sandbox Code Playgroud)
对于每个单词,您可以使用:
TextView textView = (TextView)findViewById(R.id.mytextview01);
//use a loop to change text color
Spannable WordtoSpan = new SpannableString("partial colored text");
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(WordtoSpan);
Run Code Online (Sandbox Code Playgroud)
如果我能理解你有单词列表,并且你想在文本中找到这些单词并突出显示它们,那么在这个答案中你有三个输入参数:
yourTextview 显示结果文本
String text = "full of your text";
Spannable textSpannable = new SpannableString(text);
for (int j =0 ; j<yourList.size() ; j++) {
//word of your list
String word = String.valueOf(yourList.get(j));
//find index of words
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {
//find the length of word for set color
int last = i + word.length();
//set text color with spannable
textSpannable.setSpan(new BackgroundColorSpan(Color.parseColor("#0cab8f")),
i, last, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
yourTextView.setText(textSpannable);
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
5717 次 |
| 最近记录: |