Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 713
koti Avatar asked Dec 15 '22 03:12

koti


2 Answers

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);
}
like image 55
vipul mittal Avatar answered Apr 19 '23 23:04

vipul mittal


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));
like image 42
dipali Avatar answered Apr 20 '23 00:04

dipali