1

I have code to search a TextView and return the searched word with a highlight. The problem is that it keeps the previously searched words highlighted too, instead of starting highlighting anew. Following is my code:

            String ett = et.getText().toString();
            String tvt = tvdisplay.getText().toString();
            int ofe = tvt.indexOf(ett,0);

          Spannable WordtoSpan = new                 SpannableString(tvdisplay.getText());
             for (int ofs=0; ofs<tvt.length() && ofe != -1; ofs=ofe+1)
             {

                 ofe = tvt.indexOf(ett, ofs);
                 if (ofe == -1)
                     break;
                 else
                 {

                     WordtoSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00),ofe,ofe+ett.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                     tvdisplay.setText(WordtoSpan, TextView.BufferType.SPANNABLE);
                 }
             }

        }
    });

    }

Image of the searched words in the emulator: enter image description here

CinCout
  • 9,486
  • 12
  • 49
  • 67
Pamela Sillah
  • 193
  • 4
  • 17

1 Answers1

0

Instead of using new SpannableString(tvdisplay.getText()) use new SpannableString(tvt)

What you want to do is create the new Spannable from the text String, and not from the CharSequence. But the problem here is that tvdisplay.getText() returns a CharSequence - in this case it returns the SpannableString you previously set.

If performance is a critical point to your app, you might consider removing the old span with removeSpan() instead of creating a new SpannableString object every time. For more info on Strings, CharSequences etc. in general check out https://stackoverflow.com/a/17547344/1096567

Community
  • 1
  • 1
Lovis
  • 9,513
  • 5
  • 31
  • 47
  • Problem solved. That does the trick. How do I make it case insensitive though? If I use caps on a word that is there, it returns no result – Pamela Sillah Feb 02 '16 at 15:37
  • @PamelaSillah create the SpannableString as I wrote above, but perform the search with lowercase versions of the search word and the text (but beware that toLowercase and toUppercase might not work as you expect in some languages). – Lovis Feb 02 '16 at 16:09