Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change text color of one word in a TextView

I am looking for a way to change the color of a text of a single word in a TextView from within an Activity.

For example, with this:

String first = "This word is "; String next = "red" TextView t = (TextView) findViewById(R.id.textbox); t.setText(first + next); 

How would I change the color of the next text to red?

like image 718
cerealspiller Avatar asked Aug 28 '11 15:08

cerealspiller


2 Answers

Easiest way I know is to just use html.

String first = "This word is "; String next = "<font color='#EE0000'>red</font>"; t.setText(Html.fromHtml(first + next)); 

But this will require you to rebuild the TextView when (if?) you want to change the color, which could cause a hassle.

like image 85
Dan Avatar answered Sep 30 '22 07:09

Dan


t.setText(first + next, BufferType.SPANNABLE); Spannable s = (Spannable)t.getText(); int start = first.length(); int end = start + next.length(); s.setSpan(new ForegroundColorSpan(0xFFFF0000), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 

you have to use spannable this will also allows you to increase some text's size, make it bold etc.... even put in some image.

like image 44
codeScriber Avatar answered Sep 30 '22 07:09

codeScriber