0

I have a TextView with text and a Button that when i press highlight the word hello if it finds it in the text . working on a project in the android studio and I'm totally novice so if u can help point me in the right direction thx in advanced. for now, my app only highlight the word - hello

example : String textToHighlight = "hello";

How can I make it highlight the list of words from a file or database or just a simple line of code example : in the TextView there words " hello people i love u all " and I want to highlight hello and love

Saikrishna Rajaraman
  • 3,205
  • 2
  • 16
  • 29
yan
  • 1
  • 1
    Android allows to display HTML in TextView, so maybe you can construct dynamic HTML and set it on your TextView. This is one link for your reference. https://stackoverflow.com/questions/2116162/how-to-display-html-in-textview – Alok Gupta Feb 16 '19 at 09:55
  • Possible duplicate of [How to display HTML in TextView?](https://stackoverflow.com/questions/2116162/how-to-display-html-in-textview) – Reaz Murshed Feb 16 '19 at 09:58

2 Answers2

1

You probably want to use a SpannableString for this, which allows individual parts of a string to be rendered differently in a TextView.

Like so:

SpannableString str = new SpannableString("Highlighted. Not highlighted.");
str.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 11, 0);
textView.setText(str);
Akash Pal
  • 1,055
  • 8
  • 15
0

you can work with Span's Span in android is the way to giving color-font-background-etc to the pic's of the text inside the textview family here is great article about Spans

https://blog.stylingandroid.com/introduction-to-spans/

Amir Hossein Mirzaei
  • 2,325
  • 1
  • 9
  • 17
  • 1
    I know it took long time for me but I am using span like u said , thx for that . – yan Mar 09 '19 at 14:15
  • Another Q , I have like 100 words to find in the textview What is faster to work with SQL or 100 lines of code for each word ? – yan Mar 10 '19 at 05:18
  • @yan in my opinion using sql database just for handling this operation is bad you can use Regex to search through your text – Amir Hossein Mirzaei Mar 10 '19 at 06:52
  • now i am using ssBuilder.setSpan( new ForegroundColorSpan(Color.RED), text.indexOf("hello"), text.indexOf("hello") + String.valueOf("hello").length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ); and i have like 100 diffrenet words to find , how Regex can help – yan Mar 10 '19 at 18:13