Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to color part of TextView in android? [duplicate]

I am trying to change the color of certain words (Search results) in a TextView? I tried to use ANSI colors like this:

text.setText("\u001B31;1m" + "someText");

but it did not work. How do I achieve this?

like image 687
Kalimah Avatar asked Sep 08 '11 11:09

Kalimah


3 Answers

this will help u

Spannable WordtoSpan = new SpannableString("I know just how to whisper");        
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 5, 13, 
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textview.setText(WordtoSpan);
like image 111
RajaReddy PolamReddy Avatar answered Oct 04 '22 19:10

RajaReddy PolamReddy


You're looking for TextAppearanceSpan and 'SpannableString' To be more clear workflow is as follow

  1. Create SpannableString from your source String
  2. Create TextAppearanceSpan and set it via call to setSpan method on SpannableString
  3. Call textView.setText method with SpannableString as argument
like image 21
Nikolay Ivanov Avatar answered Oct 04 '22 18:10

Nikolay Ivanov


You can also use HTML like in the following example:

string = "<font color='#FFFFFF'>This is my text </font>" + "<font color='#000000'> Another text </font>";
textView.setText(Html.fromHtml(string));

Without using additional variable (one-line solution):

textView.setText(Html.fromHtml("<font color='#FFFFFF'>This is my text </font>" + "<font color='#000000'> Another text </font>"));

It is quite easy and understandable solution :)

like image 21
Marek Avatar answered Oct 04 '22 19:10

Marek