Android CodeView: Highlight search result in List Items

Amr Hesham
ITNEXT
Published in
3 min readJun 5, 2021

--

Hello developers, in the last two articles I published about how to use CodeView to create your own Code Editor and you can read it from here, about many features that can be implemented using CodeView such as highlight text in paragraphs, also highlight hashtags, emails, URL’s you can read it from here.

In this article I will show you how to use CodeView to highlight searching result in List Items such as RecyclerView, GridView or ListView items easily and with many features, our final result will be like this, so lets start coding.

highlight search result

CodeView make it easy for everyone to implement highlighting features, I will left designing your List item and your app colors to choose what you love, our work will be in the Adapter and SearchView when the search query updated.

In your adapter you need to create global variable that will contains the search pattern, if it equal null that mean we don’t need to highlight anything, and Color object to store the color of highlighted keywords and we will make it MAGENTA by default, you can create setter method to change it any time you want or depend on your app theme.

private Pattern syntaxPattern;
private Color highlightColor = Color.MAGENTA;

And we will create setter method to update the current pattern depend on the search keyword.

public void updateSyntaxPattern(Pattern pattern) {
syntaxPattern = pattern;
notifyDataSetChanged();
}

When you set the text for each item, depend on your Adapter, for example in ArrayAdapter that will be in getView method and in RecyclerViewAdapter that may be in your holder …etc.

We will simply check if our pattern is not null and just add it to the CodeView instance with the color, but remember we need to clean the pattern from the last search, so the code will be like.

if(syntaxPattern != null) {
codeView.resetSyntaxPatternList();
codeView.addSyntaxPattern(syntaxPattern, highlightColor);
}

and now we done in the Adapter, lets go to the SearchView, you have to two methods to use onQueryTextSubmit and onQueryTextChange, depend on when you want the highlighter to work you will choose one of them, then just set the pattern by using out helper method from the Adapter, so the code will be like this,

Pattern pattern = Pattern.compile(query);
adapter.updateSyntaxPattern(pattern);

That’s it, now our feature is done, you can extend it and add extra features like multiple highlighters, or change the color in the runtime to support multiple themes …etc.

It’s very easy to use, well documented, has many examples on GitHub you can know how to download and use from GitHub link:
https://github.com/amrdeveloper/codeview

and I hope you will enjoy creating your editor with CodeView 😋.

You can find me on: Github, Linkedin, Twitter.

Enjoy Programming 😋.

--

--