String highlightedWords[] = {"We", "country"};
String fullText = "We love our country a lot.";
输出将如下所示:我们非常爱我们的国家。
您可以像下面一样实现相同的目标
//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);
最适合
我的解决方案,也是最优雅的解决方案
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);