I have implemented a search mechanism in my app such that, when you filter through the names in the list, it highlights the names that match, with only issue being it only highlights the lowercase letters and doesn't highlight any words that are in uppercase or followed by an uppercase alphabet.
Here's my code to highlight the searched characters:
if(! searchText.isEmpty()) {
if(guest.getGuestFirstName().contains(searchText)){
int startPos = guest.getGuestFirstName().indexOf(searchText.toLowerCase(Locale.US));
int endPos = startPos + searchText.length();
if (startPos != -1) // This should always be true, just a sanity check
{
Spannable spannable = new SpannableString(guest.getGuestFirstName());
Typeface firstNameFont = Typeface.createFromAsset(context.getAssets(), "fonts/Graphik-Semibold.otf");
spannable.setSpan(new CustomTypefaceSpan("", firstNameFont), startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
guestFirstName.setText(spannable);
}
} else {
Objects.requireNonNull(guestFirstName).setText(guest.getGuestFirstName());
}
Now if I search for "an", it will highlight the "an" characters in "angela heely" but if I search for "An", it will not highlight any characters at all or vice versa, say if "Angela Heely" begins with a capital letter and I search with "an" ,it won't highlight " An". Might be something simple I am missing, but any help or ideas would be appreciated to make it case insensitive to highlight the searched text.
Open to any regex expressions too. Right now searchtext string, returns whatever the user searched for irrespective of case. say " angela" , "an" etc
Thanks!!
Your problem is with the contains in that line:
if(guest.getGuestFirstName().contains(searchText)){
contains is case sensitive so "an" and "An" are not the same. change it to this:
if(guest.getGuestFirstName().toLowerCase().contains(searchText.toLowerCase())){
Also, change this:
int startPos = guest.getGuestFirstName().indexOf(searchText.toLowerCase(Locale.US));
to this (from the same reason):
int startPos = guest.getGuestFirstName().toLowerCase().indexOf(searchText.toLowerCase());