-4
String highlightedWords[] = {"We", "country"};

String fullText = "We love our country a lot.";

output will be like this: We love our country a lot.

Ahamadullah Saikat
  • 4,437
  • 42
  • 39

2 Answers2

2

You can achieve the same like below

 //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);
Vir Rajpurohit
  • 1,869
  • 1
  • 10
  • 23
1

Solution that worked best for me and was the most elegant one

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);
t0milee
  • 9
  • 1
  • for "int indexOfWord..." did you mean to call it "indexOfKeyword"? Because later you use "setSpan(...,indexOfKeyword, indexOfKeyword + ..."); – AJW May 10 '21 at 17:36