微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐