在我的Android应用程序中,我有一个包含特定单词的字符串,所以我想在文本视图中显示整个字符串,并且应该突出显示特定的单词。希望下面的图片会给你一个想法。
我使用了以下代码来执行此操作,但它无效。
CODE:
con是我的字符串,groupNameContent是文本字段。
con.replaceAll(arrGroupelements[groupPosition][5],"<font color='#CA278C'>"+arrGroupelements[groupPosition][5]+"</font>.");
groupNameContent.setText(Html.fromHtml(con));
答案 0 :(得分:7)
对于每个单词,您可以使用:
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);
答案 1 :(得分:3)
如果我能理解你有单词列表,并且想要在文本中找到这些单词并突出显示它们,那么在这个答案中你有三个输入参数:
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);
答案 2 :(得分:-1)
为了简单起见,我在这里发布我的方法
。 。 。 。 。 。 。
首先准备使用方法
ArrayList<String> searchWords = new ArrayList<String>(Arrays.asList("Second", "Scottish", "forces", "England"));
String text = "1333 – Second War of Scottish Independence: The Scottish-held town of Berwick-upon-Tweed surrendered to English forces, ending a siege led by Edward III of England (depicted).";
TextView sampleTextView = new TextView(currentContext); // currentContext = getContext();
if (searchWords != null) {
Spannable newText = setSpanHighlight(text, searchWords);
sampleTextView.setText(newText, TextView.BufferType.SPANNABLE);
}
else{
sampleTextView.setText(text);
}
方法
private Spannable setSpanHighlight(String text, @NonNull ArrayList<String> searchWord) {
Spannable newText = new SpannableString(text);
if (searchWord.size() != 0) {
for (String word : searchWord){
if (text.contains(word)){
int beginIndex = text.indexOf(String.valueOf(word)); //Unnecessary 'String.valueOf()' call => if you have something else than String
int endIndex = beginIndex + word.length();
newText.setSpan(
new ForegroundColorSpan(Color.BLUE),
beginIndex,
endIndex,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
return newText;
}