Android: Coloring part of a string using TextView.setText()?
If you are using Kotlin you can do the following using the android-ktx library
val title = SpannableStringBuilder()
.append("Your big island ")
.bold { append("ADVENTURE") }
titleTextField.text = title
The bold
is an extension function on SpannableStringBuilder
. You can see the documentation here for a list of operations you can use.
Another example:
val ssb = SpannableStringBuilder()
.color(green) { append("Green text ") }
.append("Normal text ")
.scale(0.5F) { append("Text at half size ") }
.backgroundColor(green) { append("Background green") }
Where green
is a resolved RGB color.
It is even possible to nest spans so you end up with something like an embedded DSL:
bold { underline { italic { append("Bold and underlined") } } }
You will need the following in your app module level build.gradle
for it to work:
repositories {
google()
}
dependencies {
implementation 'androidx.core:core-ktx:0.3'
}
title.setText(Html.fromHtml("Your big island <b>ADVENTURE!</b>"));
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);
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).