GeekedOut
GeekedOut

Reputation: 17185

Android - is there a way to edit color in a part of a string that is displayed?

I have a part of the code that calls a toString on an object and the toString basically spits out the string that will be shown on the screen.

I would like to change the color of one part of the string.

I just tried something like this:

        String coloredString =  solutionTopicName + " (" + commentCount +  ")";
        Spannable sb = new SpannableString( coloredString );
        ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(140, 145, 160));
        sb.setSpan(new ForegroundColorSpan(Color.BLUE), solutionTopicName.length(), solutionTopicName.length()+3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        return sb.toString();   

But I am still seeing the same colors appear without change.

Thanks!

Upvotes: 0

Views: 642

Answers (2)

yes, it is possible

use Spannable to do that.

setSpan() will do the job.

Spannable mString = new SpannableString("multi color string ");        

mString.setSpan(new ForegroundColorSpan(Color.BLUE), 5, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

Update:

String coloredString = " (" + solutionTopicName + commentCount +  ")";
        Spannable sb = new SpannableString( coloredString );
        ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(140, 145, 160));
        sb.setSpan(new ForegroundColorSpan(Color.BLUE), solutionTopicName.length(), solutionTopicName.length()+3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        //textView.setText(sb);
    return sb;

Latest:

 String solutionTopicName= "Hello";
 String commentCount= "hi how are you";
 String coloredString =  solutionTopicName+"(" + commentCount +  ")";
 Spannable sb = new SpannableString( coloredString );
 sb.setSpan(new ForegroundColorSpan(Color.BLUE), coloredString.indexOf("("), coloredString.indexOf(")")+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  mTextView.setText(sb);

Upvotes: 2

N-JOY
N-JOY

Reputation: 7635

I would like to change the color of one part of the string. Is that at all possible?

yes, you can change color of specific part of string. There is a SpannableStringBuilder class you can make use of it.

you can do some thing like this.

SpannableStringBuilder sb = new SpannableStringBuilder("This is your String");
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(140, 145, 160));
sb.setSpan(fcs, 0, 10, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(sb);  

here is the definition of setspan method.

setSpan(Object what, int start, int end, int flags)
Mark the specified range of text with the specified object.  

setSpan method takes indices as parameter and an instance of Object Class. so any class' instance could be passed in as parameter depending upon your requirement. we used instance of ForegroundColorSpan to change color of text. you can pass Clickable instance to make certain part of string clickable.

Upvotes: 1

Related Questions