Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Coloring part of a string using TextView.setText()?

I am looking to change the text of a TextView view via the .setText("") method while also coloring a part of the text (or making it bold, italic, transparent, etc.)and not the rest. For example:

title.setText("Your big island <b>ADVENTURE!</b>";

I know the above code is incorrect but it helps illustrate what I would like to achieve. How would I do this?

like image 525
Jared Avatar asked Feb 04 '11 11:02

Jared


People also ask

How can I change the color of a part of a TextView?

One way is to split myTextView to few separate TextViews , one of which would be only for phone code. Then controlling color of this specific TextView is pretty straight-forward. Nah, pain in the ass. Using a spannable is the right way.

How do you change the color of a Spannable string?

For example, to set a green text color you would create a SpannableString based on the text and set the span. SpannableString string = new SpannableString("Text with a foreground color span"); string. setSpan(new ForegroundColorSpan(color), 12, 28, Spanned. SPAN_EXCLUSIVE_EXCLUSIVE);

How do you change the color of your text on android?

Open your device's Settings app . Text and display. Select Color correction. Turn on Use color correction.

How do I change the text color of Spannable string in android?

MainActivity. SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text2); // It is used to set foreground color. ForegroundColorSpan green = new ForegroundColorSpan(Color. GREEN);


3 Answers

Use spans.

Example:

final SpannableStringBuilder sb = new SpannableStringBuilder("your text here");

// Span to set text color to some RGB value
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(158, 158, 158)); 

// Span to make text bold
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); 

// Set the text color for first 4 characters
sb.setSpan(fcs, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

// make them also bold
sb.setSpan(bss, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

yourTextView.setText(sb);
like image 148
Alex Orlov Avatar answered Oct 06 '22 22:10

Alex Orlov


title.setText(Html.fromHtml("Your big island <b>ADVENTURE!</b>")); 
like image 23
sat Avatar answered Oct 06 '22 22:10

sat


I hope this helps you (it works with multi language).

<string name="test_string" ><![CDATA[<font color="%1$s"><b>Test/b></font>]]> String</string>

And on your java code, you can do:

int color = context.getResources().getColor(android.R.color.holo_blue_light);
String string = context.getString(R.string.test_string, color);
textView.setText(Html.fromHtml(string));

This way, only the "Test" part will be colored (and bold).

like image 26
Luis Avatar answered Oct 06 '22 22:10

Luis