-1

I have a scrollable TextView that has texts like this

...
Tom: sometext
Jack: anothertext
Sam: something
...

So I get this data as a JSON object, then I seperate the keys and values, then adding to a string. Then I set the text of TextView as this final string.

What I want is, I would like to make different colors for Tom, Jack, Sam. I have found HTML library but all solutions changes the whole TextView. I want to change specific parts of the text and since I get a JSON data first and I'm adding this JSON values to a string part by part, I thought I can do something like this string += <HTML color change> JSON["key"] + JSON["anotherKey"].

Is it possible to change specific parts of the text of a TextView object?

David Wasser
  • 93,459
  • 16
  • 209
  • 274
GLHF
  • 3,835
  • 10
  • 38
  • 83
  • Removed tag `android-studio` as this tag is used for problems/questions related to the Android Studio product. Your question is an Android question and has nothing to do with the Android Studio product. – David Wasser May 14 '21 at 20:10
  • 1
    You mean that [this](https://stackoverflow.com/a/6094346/15298643) didn't work? – javdromero May 14 '21 at 20:24
  • @javdromero yes that didn't work – GLHF May 14 '21 at 21:29

2 Answers2

0

Take a look at spannable Strings. You will probably end up with something like this.

val spannable = SpannableStringBuilder("Text " + JSON["key"])
spannable.setSpan(
    ForegroundColorSpan(Color.RED),
    5, // start
    5 + JSON["key"].length, // end
    Spannable.SPAN_EXCLUSIVE_INCLUSIVE
)

See https://developer.android.com/guide/topics/text/spans for more info regarding spans.

Note: this example is in Kotlin but it's pretty much the same in Java.

Kilian
  • 275
  • 2
  • 8
0

You can change text color in TextView using below code snippets.

val blackColor= ContextCompat.getColor(context, R.color.black)
val redColor= ContextCompat.getColor(context, R.color.red)

textView.text = HtmlCompat.fromHtml("<font color=\"$blackColor\">Welcome to </font> <font color=\"$redColor\">Stack Overflow </font>", HtmlCompat.FROM_HTML_MODE_LEGACY)

Above code is in kotlin , its same as Java you can convert to Java. Hope it will work for you !

Nitin Karande
  • 1,280
  • 14
  • 33