1

I want to mark in yellow some word inside a textview, like whatsapp did in their application. What I've tried was to use html tag:

tv.setText("<mark> hello </mark> world"); but it doesn't work, it doesn't mark the word and the tags are part from the text.

Elior
  • 3,178
  • 6
  • 37
  • 67

4 Answers4

3

Let's say you have a TextView tv, and you want to set yellow color to the text "hello" of "hello world".

TextView tv = (TextView) findViewById(R.id.textView);

Spannable word = new SpannableString("hello world");

word.setSpan(new ForegroundColorSpan(Color.YELLOW), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

tv.setText(word);

In third line, I'm setting YELLOW color to the word "hello". "hello" starts from index position 0 and ends in index position 5. After setting the span, set the Spannable word as text of TextView tv.

Here's documentation on setSpan()

setSpan (Object what, int start, int end, int flags)

Attach the specified markup object to the range start…end of the text, or move the object to that range if it was already attached elsewhere. See Spanned for an explanation of what the flags mean. The object can be one that has meaning only within your application, or it can be one that the text system will use to affect text display or behavior. Some noteworthy ones are the subclasses of CharacterStyle and ParagraphStyle, and TextWatcher and SpanWatcher.

Spannable section

This is the interface for text that has markup objects attached to ranges of it. Not all text classes have mutable markup or text

capt.swag
  • 10,335
  • 2
  • 41
  • 41
1

You need to create Spannable and specify color for specific text range. Like in the following answer: https://stackoverflow.com/a/3514435/1099716

Community
  • 1
  • 1
Access Denied
  • 8,723
  • 4
  • 42
  • 72
1

Try this,

myTextView.setText(Html.fromHtml(text + "<font color=white>" + CepVizyon.getPhoneCode() + "</font><br><br>"
        + getText(R.string.currentversion) +someString));
Parag Kadam
  • 3,620
  • 5
  • 25
  • 51
1

All the other answers are relevant, and are personally what I would use, but in the interest of increased flexibility note that it is also possible to apply html formatting with the Html class:

tv.setText(Html.fromHtml("<font color='red'>Coloured Text</font>"))
PPartisan
  • 8,173
  • 4
  • 29
  • 48