Home > other >  How to give specific colors to words using Spannable?
How to give specific colors to words using Spannable?

Time:11-15

I have a TextView and contains the below text

The -[[community]]- is here to help you with -[[specific]]- coding, -[[algorithm]]-, or -[[language]]- problems.

I want anything inside -[[]]- take red color, How can I do that using Spannable?

And I don't want to show -[[ and ]]- in TextView

CodePudding user response:

You can use SpannableStringBuilder and append parts of String colorizing them when necessary. For example,

static CharSequence colorize(
        String input, String open, String close, @ColorInt int color
) {
    SpannableStringBuilder builder = new SpannableStringBuilder();
    int openLen = open.length(), closeLen = close.length();
    int openAt, contentAt, closeAt, last = 0;
    while ((openAt = input.indexOf(open, last)) >= 0 &&
            (closeAt = input
                    .indexOf(close, contentAt = openAt   openLen)) >= 0) {
        int start = builder.append(input, last, openAt).length();
        int len = builder.append(input, contentAt, closeAt).length();
        builder.setSpan(
                new ForegroundColorSpan(color),
                start, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        );
        last = closeAt   closeLen;
    }
    return builder.append(input, last, input.length());
}

CodePudding user response:

You can use the CodeView library to highlight many patterns with different colors, in your case for example the code will be like this

CodeView codeView = findViewById(R.id.codeview);
codeView.addSyntaxPattern(Pattern.compile("-\\[\\[[a-zA-Z] ]]-"), Color.GREEN);
codeView.setTextHighlighted(text);

And the result will be:

enter image description here

If the highlighted keywords are unique you can highlight them without using -[[]]- just create a pattern that can cover them

You can change the color, add or remove patterns in the runtime

CodeView Repository URL: https://github.com/amrdeveloper/codeview

  • Related