更改文本TextView中特定单词的背景颜色

muz*_*diq 7 android

我想改变特定单词的背景颜色TextView :

如下图所示

在此输入图像描述

BNK*_*BNK 6

这是我的工作代码,可用于突出显示字符串的某些部分:

     private void highlightTextPart(TextView textView, int index, String regularExpression) {
        String fullText = textView.getText().toString();
        int startPos = 0;
        int endPos = fullText.length();
        String[] textParts = fullText.split(regularExpression);
        if (index < 0 || index > textParts.length - 1) {
            return;
        }
        if (textParts.length > 1) {
            startPos = fullText.indexOf(textParts[index]);
            endPos = fullText.indexOf(regularExpression, startPos);
            if (endPos == -1) {
                endPos = fullText.length();
            }
        }
        Spannable spannable = new SpannableString(fullText);
        ColorStateList blueColor = new ColorStateList(new int[][] { new int[] {}}, new int[] { Color.BLUE });
        TextAppearanceSpan textAppearanceSpan = new TextAppearanceSpan(null, Typeface.BOLD_ITALIC, -1, blueColor, null);
        BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(Color.GREEN);
        spannable.setSpan(textAppearanceSpan, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannable.setSpan(backgroundColorSpan, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(spannable);
    }
Run Code Online (Sandbox Code Playgroud)

然后在您的活动中,如下调用:

    int index = 3;
    String regularExpression = " ";
    String text = "Hello StackOverflow From BNK!";
    TextView textView = (TextView) findViewById(R.id.textView);
    if (textView != null) {
        textView.setText(text);
        highlightTextPart(textView, index, regularExpression);
    }
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明