Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

java - How to use SpannableString with Regex in android?

I am trying to color part of a string using spannableString and regular expressions in Android using this function:

public static String StringReplace(String source) {
        String find = "ABC";
        SpannableString replace = new SpannableString(find);        
        replace.setSpan(new ForegroundColorSpan(Color.RED), 0, 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

        String output = source.replace(find, replace);
        return  output;
    }

Because the function replace() returns a string I am not able to get a colored string. My question is: what is the best way to color part of a text using regexp?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Updated 10th Sept - changes all occurrences of target string

Something generic like this will work:

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 
So does this :ABCDEF - see!
And 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);
    }

}

.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...