Question

I am looking for a way to find different strings on a TextView and replace them with styled SpannableStrings.

I found this code in How to use SpannableString with Regex in android? that does just that for a single string:

public class SpanTest extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String dispStr = "This has the string ABCDEF in it \nSo does this :ABCDEF - see!\nAnd again ABCD here";
        TextView tv = (TextView) findViewById(R.id.textView1);
        tv.setText(dispStr);
        changeTextinView(tv, "ABC", Color.RED);
    }

    private void changeTextinView(TextView tv, String target, int colour) {
        String vString = (String) tv.getText();
        int startSpan = 0, endSpan = 0;
        Spannable spanRange = new SpannableString(vString);

        while (true) {
            startSpan = vString.indexOf(target, endSpan);
            ForegroundColorSpan foreColour = new ForegroundColorSpan(colour);
            // Need a NEW span object every loop, else it just moves the span
            if (startSpan < 0)
                break;
            endSpan = startSpan + target.length();
            spanRange.setSpan(foreColour, startSpan, endSpan,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        tv.setText(spanRange);
    }

}

This works great but I'm not sure how to adapt it to use if with multiple strings. I tried to re-implement it using SpannableStringBuilder.replace so I can run the method multiple times while keeping the previous style but have failed.

Any Ideas?

Thanks!

Was it helpful?

Solution

This works great but I'm not sure how to adapt it to use if with multiple strings.

Off the cuff...

Step #1: Change changeTextinView() to take a SpannableString as the first parameter, instead of a TextView.

Step #2: Modify onCreate() to create a SpannableString from dispStr and pass that to changeTextinView(), then take the SpannableString and pass it to setText() on the TextView.

At this point, it should work as it did before, except that you will be in position to do:

Step #3: Call changeTextinView() several times in succession, once per string.

Things will get somewhat messy if there is overlap (e.g., you want to format ABCDEF one way and CDE another way), but I am hoping that is not the case for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top