String highlightedWords[] = {"We", "country"};
String full_text = "We love our country a lot. Our country is very good.";
textview.setText(full_text);
输出: 我们非常喜欢我们的国家/地区。我们的国家非常好。
如何在SpannableString中突出显示这些单词
答案 0 :(得分:1)
您可以达到以下相同的目标
//Create new list
ArrayList<String> mList = new ArrayList<>();
//Words to split
String words[] = {"We", "country"};
//main string
String full_text = "We love our country a lot.";
//split strings by space
String[] splittedWords = full_text.split(" ");
SpannableString str=new SpannableString(full_text);
//Check the matching words
for (int i = 0; i < words.length; i++) {
for (int j = 0; j < splittedWords.length; j++) {
if (words[i].equalsIgnoreCase(splittedWords[j])) {
mList.add(words[i]);
}
}
}
//make the words bold
for (int k = 0; k < mList.size(); k++) {
int val = full_text.indexOf(mList.get(k));
str.setSpan(new StyleSpan(Typeface.BOLD), val, val + mList.get(k).length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
//set text
((TextView)findViewById(R.id.tvSample)).setText(str);
答案 1 :(得分:1)
最适合我的解决方案,也是最优雅的解决方案
ArrayList<String> wordsToHighlight = new ArrayList<>(Arrays.asList("We", "country");
String fullText = "We love our country a lot. Our country is very good.";
SpannableString spannableString = new SpannableString(fullText);
ArrayList<String> brokenDownFullText = new ArrayList<>(Arrays.asList(fullText.split(" ")));
brokenDownFullText.retainAll(wordsToHighlight);
for (String word : brokenDownFullText) {
int indexOfWord = fullText.indexOf(word);
spannableString.setSpan(new StyleSpan(Typeface.BOLD), indexOfKeyword, indexOfKeyword + word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
textView.setText(spannableString);