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

Muh*_*mar 5 java eclipse android android-studio

我有一个字符串

1 Friend | O Reviews | 0 Coupons
Run Code Online (Sandbox Code Playgroud)

我正在使用以下代码

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);
Run Code Online (Sandbox Code Playgroud)

我想改变 | 的颜色 从 TextView 原来的灰色变为蓝色。上面的代码什么也没做。我在其中做错了什么。

Ami*_*pta 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);
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述