Reputation: 329
I am building an application where a user using a search feature to check a particular word exist in the database or not. In backend process, I use a like query to filter out the proper result and displayed it in list-view.
In list-view, there is a text-view where the information is displayed and that particular word is in that text-view using setSpan I highlight that particular word with a specified color like below.
highlightedWord.setSpan(new BackgroundColorSpan(0xFFFFFF00) , 0, highlightedWord.length(),
SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.messageTxt.setMovementMethod(LinkMovementMethod.getInstance());
holder.messageTxt.setHighlightColor(Color.YELLOW);
holder.messageTxt.setText(firstString);
holder.messageTxt.append(highlightedWord);
holder.messageTxt.append(secondString);
It works well till here.
First Problem: Now the problem is if there is an information of 10 line or more and my text-view is set to max-Line one. So the only first line is displayed in my text-view due to this If that particular word is in below the first line it does not highlight nore displayed. I need to display that particular line in my text-view. Example if you search in any message application it arrange the word as per it.
Second Problem: If I am using setSpan it is not case-insensitive. It does not highlight the word with capital or small when the search word is vice-versa. Like if I search test and Test is there it will not highlight that word and If now I search Test it will highlight that same word.
Upvotes: 1
Views: 2186
Reputation: 358
You can try this. It will highlight all the text matching with your word.
origString = origString.replaceAll(textToHighlight,"<font color='red'>"+textToHighlight+"</font>");
Textview.setText(Html.fromHtml(origString));
Upvotes: 0
Reputation: 424
I made this method recently to highlight specific parts of a string for a textview.
public static SpannableString colorString(int color, String text, String...wordsToColor) {
SpannableString coloredString = new SpannableString(text);
for(String word : wordsToColor) {
int startColorIndex = text.indexOf(word);
int endColorIndex = startColorIndex + word.length();
coloredString.setSpan(new ForegroundColorSpan(color), startColorIndex, endColorIndex,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return coloredString;
}
This method allows you to pass in a color, the full text of the string and the word of the string you want highlighted with the color. It can be used as follows.
textView.setText(colorString(ContextCompat.getColor(context, R.color.colorPrimaryLink),
fullString, highlightedWord1, highlightedWord2));
Upvotes: 1
Reputation: 6245
You can use holder.messageTxt.setText(Html.fromHtml(firstString +"<i>"+highlight+"</i>" + secondString));
Simple html formatting
Upvotes: 0
Reputation: 12300
Upvotes: 0