How to Search and Highlight text in Android

This is a quick tutorial on how to highlight all the occurrences of a keyword provided by the user during a search.

We will use SpannableString to achieve this.

First set up a basic layout with a EditText and a TextView. Below is the XML for the same.

When you run the app, it will look like this

highlight

Now reference these views in the Activity

Now add a TextWatcher on the EditText to listen to text change events. Call a function called highlightString(String s) in the onTextChanged of the TextWatcher, this will be the function that contains the highlighting code.

Now comes the main and the fun part. Let’s highlight some text!

Add the following function to your activity. Don’t worry, I’ll explain every bit of it!

Let’s break down and understand this code line by line.

  • First we are getting the input i.e. the keyword to be highlighted as a parameter.
  • Then we are creating a SpannableString by getting the text from the TextView.
  • Pay attention, Now we are removing all the spans i.e. all the highlighted parts from the previous search of the user, if we don’t do this then we will end up with a mess of highlighted strings that the user didn’t even searched. So we get all the spans of type BackgroudColorSpan and loop over the array, removing all of them one by one by calling the .removeSpan function on the spnnableString.
  • Now with spnnableString.toString().indexOf(input) we find the first index of the keyword.
  • Then inside the while loop we set a new span on the spannableString of type BackgroundColorSpan(Color.Yellow), the 2nd and the 3rd argument tell which part of the string should this span be applied to i.e. the start index and end index. The 4th argument is a span flag.
  • Now we find the next occurrence of the keyword to be highlighted by using the same .indexOf method but this time passing a 2nd parameter to tell it from where to start searching for the keyword.
  • At last we set the spannableString to the TextView.

Now when you run and search for a text all the occurrences of it will be highlighted

highlight

Leave a Reply

Your email address will not be published. Required fields are marked *