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

583 Views Asked by At

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.
2

There are 2 best solutions below

0
On BEST ANSWER

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);
1
On

The only way I could think of is using SpannableStringBuilder. A Spannable is a CharSequence and textview.getText() returns a CharSequence too. If you avoid the toString conversion the style will not be lost. SpannableStringBuilder has also a replace function