繁体   English   中英

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

[英]Changing Color Of TextView text in android using spannableString

我有一个字符串

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

称这种方法为

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM