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

时间:2016-05-08 04:21:05

标签: java android eclipse android-studio

我有一个字符串

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 个答案:

答案 0 :(得分: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);
}

答案 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);

输出:

enter image description here

答案 2 :(得分: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,"|");