0

Hi guys I want to change the colour of specific words that are starts from the @ or # in the string just like abc@yahoo.com i want to change all the character that is after and also show it into textview @enter image description here

String[] parts=str.split(" ");
        for (int i = 0; i < parts.length; i++) {
            if(parts[i].startsWith("@") || parts[i].startsWith("#"))
            {

                System.out.println(part[i]);

            }

this will give me tokens but i want to show the whole string with modify words

3 Answers3

0

try to use below given code

     String[] parts=str.split(" ");
       for (int i = 0; i < parts.length; i++) {
        if(parts[i].startsWith("@") || parts[i].startsWith("#"))
        {

            System.out.println(Html.fromHtml("<font color='red'>part[i]</font>"));

        }

Hopefully it will perfectly work for you.

Rituraj suman
  • 216
  • 1
  • 16
0
textView = ((TextView) view.findViewById(R.id.textView));

SpannableStringBuilder ss = new SpannableStringBuilder();
String stringText = "@ @dfdfg df@dgh fh@ # #fdf fdf#fdf fdf#";
String[] stringArray = stringText.split(" ");
Pattern pattern = Pattern.compile("^[@|#](\\w+|)");//starting with # or @ and text after
Matcher patternMatcher = null;

for (int i = 0; i < stringArray.length; i++) {
    patternMatcher = pattern.matcher(stringArray[i]);
    if (patternMatcher.find()) {
        SpannableString spannableString = new SpannableString(patternMatcher.group());
        spannableString.setSpan(new ForegroundColorSpan(Color.BLUE), 0, patternMatcher.group().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ss.append(spannableString);
    } else {
        ss.append(stringArray[i]);
    }
    if (i + 1 < stringArray.length)//add space only when this is not the end
        ss.append(" ");
}

if (patternMatcher != null)
    patternMatcher.reset();

textView.setText(ss);
deadfish
  • 11,996
  • 12
  • 87
  • 136
0
  1. Split this String into array with '@' and space.
  2. Use Spannable Text for change the colour of special words.
  3. Please refer this link to change the color of words : Set color of TextView span in Android
Community
  • 1
  • 1
Puneet Gupta
  • 101
  • 8