在Android中使用SpannableString改变TextView文本的颜色

5

我有一个字符串

1 Friend | O Reviews | 0 Coupons

我正在使用以下代码

SpannableString hashText = new SpannableString(TextUtils.concat(
                friendsText,
                " | ",
                reviewsText,
                " | ",
                couponsText
        ).toString());

        Matcher matcher = Pattern.compile("\\s* | \\s*").matcher(hashText);
        while (matcher.find())
        {
            hashText.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.blue)), matcher.start(), matcher.end(), 0);
        }

        detailsText.setText(hashText);

我想要将TextView中的“|”颜色从原来的灰色改为蓝色。 上述代码并没有起到作用。我做错了什么?
3个回答

2

请尝试一下这个:

Spannable spannable = new SpannableString(text);

int index = text.indexOf(“|”);

while ( index >= 0) {
    spannable.setSpan(new ForegroundColorSpan(Color.BLUE), index, index + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    index = text.indexOf(“|”, index + 1);
}

2

试着这样做

String text = TextUtils.join(" | ", Arrays.asList(new String[]{"1 Friend", "1 Review", "1 Coupons"}));

        Spannable spannable = new SpannableString(text);

        int index = text.indexOf('|');
        while (index >= 0) {
            spannable.setSpan(new ForegroundColorSpan(Color.BLUE), index, index + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            index = text.indexOf('|', index + 1);
        }
        detailsText.setText(hashText);

输出:

在此输入图片描述


1
“|” 在多个位置上都被放置,它可以在字符串中的任何位置工作,但对于1 |有效。 - Muhammad Umar
1
@MuhammadUmar 它适用于任何地方找到 '|'。请运行并查看输出。我为此添加了屏幕截图。 - Amit Gupta
一个很好的Span示例可以在这里看到:https://medium.com/@joseph.neeraj/android-spannable-string-example-864d4e7193bf - Neeraj

0

即使这里有被接受的答案,但我想分享最简单的方法给用户。

public void setHighLightedText(TextView tv, String textToHighlight) {
    String tvt = tv.getText().toString();
    int ofe = tvt.indexOf(textToHighlight, 0);
    Spannable wordToSpan = new SpannableString(tv.getText());

    for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
        ofe = tvt.indexOf(textToHighlight, ofs);
        if (ofe == -1)
            break;
        else {
            // you can change or add more span as per your need
            wordToSpan.setSpan(new RelativeSizeSpan(2f), ofe,ofe + textToHighlight.length(), 0); // set size
            wordToSpan.setSpan(new ForegroundColorSpan(Color.RED), ofe, ofe + textToHighlight.length(), 0);// set color
            tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
        }
    }
}

像这样调用该方法

textView.setText("1 Friend | O Reviews | 0 Coupons");
setHighLightedText(textView,"|");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接