Ahamadullah Saikat
Ahamadullah Saikat

Reputation: 4644

Android highlight multiple words

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

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

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

Upvotes: -4

Views: 995

Answers (2)

t0milee
t0milee

Reputation: 9

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);

Upvotes: 1

Vir Rajpurohit
Vir Rajpurohit

Reputation: 1937

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);

Upvotes: 2

Related Questions