It can be done in various ways,
1) Using the Html.fromHtml()
method and defining in strings.xml
the text to change the color
<string name="mi_mensaje"><![CDATA[Hola <font color=#FF0040>StackOverflow.com</font>, como te encuentras el día de hoy!]]></string>
in this way you make the change:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
textView.setText(Html.fromHtml(getString(R.string.mi_mensaje),Html.FROM_HTML_MODE_LEGACY));
} else {
textView.setText(Html.fromHtml(getString(R.string.mi_mensaje)));
}
2) Defining the text directly, using Html.fromHtml()
:
String mensaje = "Hola <font color=#FF0040>StackOverflow.com</font>, como te encuentras el día de hoy!";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
textView.setText(Html.fromHtml(mensaje,Html.FROM_HTML_MODE_LEGACY));
} else {
textView.setText(Html.fromHtml(mensaje));
}
3) Using a SpannableString
, defining a Span
with the desired color:
SpannableString mensaje = new SpannableString("Hola StackOverflow.com, como te encuentras el día de hoy!");
ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#FF0040"));// Puedes usar tambien .. new ForegroundColorSpan(Color.RED);
mensaje.setSpan(colorSpan, 5, 22, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(mensaje);
The setSpan method () define as parameters:
- The
ForegroundColorSpan
object.
- The start in the string to apply the span.
- The end of the string to apply the span.
- Flags, in this case SPAN_INCLUSIVE_INCLUSIVE , which indicates Expand to include the text inserted in its initial or final point.
The 3 options get as a result:
similar to what you have in this answer:
Bold in a part of a TextView