androidtextviewspanned

How to replace String of TextView without losing its style and color


I set HTML mode to my TextView so in my text some String is blue or green. Now I need replace "old" to "new" without losing blue and green color. If use from textview.setText(textview.getText().toString().repaceAll("old", "new")), we lose its style and color! In fact I need code that preserves the styles. Or I need replace String in Spanned without losing its style and color.

  1. I need replace String in Spanned obj
  2. I need set Spanned obj to my TextView. But I don't know any way.

Solution

  • old string is oldstr and new string is newstr

        Spanned spanned = textView.getText();
        
        CharSequence charSequence = spanned;
        SpannableStringBuilder stringBuilder = (SpannableStringBuilder) spanned;
    
        for (int i = 1; i < charSequence.length() - 6; i++) {
            if (charSequence.charAt(i) == 'o' &&
                    charSequence.charAt(i+1) == 'l' &&
                    charSequence.charAt(i+2) == 'd' &&
                    charSequence.charAt(i+3) == 's' &&
                    charSequence.charAt(i+4) == 't' &&
                    charSequence.charAt(i+5) == 'r') {
                stringBuilder.replace(i-1, i+6, "newstr");
            }
        }
    
        spanned = stringBuilder;
        textView.setText(spanned);