Is it possible to set the color of just span of text in a TextView?
I would like to do something similar to the Twitter app, in which a part of the text is blue. See image below:
Is it possible to set the color of just span of text in a TextView?
I would like to do something similar to the Twitter app, in which a part of the text is blue. See image below:
Set Color on Text by passing String and color:
Set text on TextView / Button / EditText etc by calling below code:
TextView:
Get Colored String:
Set Text on TextView:
Done
Just to add to the accepted answer, as all the answers seem to talk about
android.graphics.Color
only: what if the color I want is defined inres/values/colors.xml
?For example, consider Material Design colors defined in
colors.xml
:(
android_material_design_colours.xml
is your best friend)Then use
ContextCompat.getColor(getContext(), R.color.md_blue_500)
where you would useColor.BLUE
, so that:becomes:
Where I found that:
Another way that could be used in some situations is to set the link color in the properties of the view that is taking the Spannable.
If your Spannable is going to be used in a TextView, for example, you can set the link color in the XML like this:
You can also set it in the code with:
paste this code in ur MainActivity
I always find visual examples helpful when trying to understand a new concept.
Background Color
Foreground Color
Combination
Further Study
Here's a Kotlin Extension Function I have for this
Use it after you have set your text to the TextView like so