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

前端之家收集整理的这篇文章主要介绍了android – 更改文本TextView中特定单词的背景颜色前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在TextView中更改特定单词的背景颜色:

如下图所示

解决方法

这是我的工作代码,您可以用它来突出显示字符串的某些部分:
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,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(spannable);
    }

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

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);
    }

原文链接:https://www.f2er.com/android/309409.html

猜你在找的Android相关文章