Java 使用spannableString更改android中TextView文本的颜色

Java 使用spannableString更改android中TextView文本的颜色,java,android,eclipse,android-studio,Java,Android,Eclipse,Android Studio,我有一根绳子 1 Friend | O Reviews | 0 Coupons 我正在使用以下代码 SpannableString hashText = new SpannableString(TextUtils.concat( friendsText, " | ", reviewsText, " | ", couponsText

我有一根绳子

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的原始灰色更改为蓝色。 上面的代码什么也不做。我做错了什么。

试试这个

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);
}
像这样试试

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);
输出:


即使在这里也可以接受答案,但我想为用户分享最简单的方法

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

“|”放置在多个位置,它确实适用于1 |但适用于世界上任何地方string@MuhammadUmar无论它在哪里找到“|”都有效。请运行并查看输出。我添加了相同的屏幕截图。可以看到一个很好的跨度示例
textView.setText("1 Friend | O Reviews | 0 Coupons");
setHighLightedText(textView,"|");