koti
koti

Reputation: 1071

how to change text color in the middle of the sentence in android

I need to change the color of the String which appears randomly in a sentence.

Ex: These following sentences are what I need to display.

  1. hai #xyz how are you.

  2. i am learning #abc android.

    In this I have to change the color of the words "#xyz", "#abc" i.e, which starts with the character "#".

    I used some string functions split(), subString(). but I am not getting what i need.

so, please guide me how to solve this.

Upvotes: 4

Views: 3368

Answers (3)

vipul mittal
vipul mittal

Reputation: 17401

Use SpannableString for ex:

SpannableString ss = new SpannableString("hai #xyz how are you.");
ss.setSpan(new ForegroundColorSpan(Color.RED), 4, 9, 0);

Try following to change color of each word with #:

String s="hai #xyz how are you.";
ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
SpannableString ss = new SpannableString(s);
String[] ss = s.split(" ");
int currIndex = 0;
for (String word : ss) {
    if (word.startsWith("#")) {
        ss.setSpan(span, currIndex,currIndex+ word.length(), 0);
    }
    currIndex += (word.length() + 1);
}

Upvotes: 4

Vaibhav Agarwal
Vaibhav Agarwal

Reputation: 4499

You can easily achieve this using html tags

tv_message.setText(Html.fromHtml("<font color=\"#000000\">"+"Hi "+"</font>"+" "+"<font color=\"#EE0000\">"+"XYZ "+"</font>"+" "+"<font color=\"#000000\">"+"How are You ?  " + "</font>"));

Upvotes: 4

dipali
dipali

Reputation: 11188

you can use this code:

t.setText(first + next, BufferType.SPANNABLE);
Spannable s = (Spannable)t.getText();
int start = first.length();
int end = start + next.length();
s.setSpan(new ForegroundColorSpan(0xFFFF0000), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

or you can use html:

String first = "This word is ";
String next = "<font color='#EE0000'>red</font>";
t.setText(Html.fromHtml(first + next));

Upvotes: 4

Related Questions