是否有可能在TextView中设置文本跨度的颜色?

我想做一些类似于Twitter应用程序的事情,其中一部分文本是蓝色的。见下图:

(来源:twimg.com)


当前回答

我也有同样的问题。 @Dano的回答绝对正确。但这对我没用。 之后,我发现问题,我已经添加ClickableSpan。它会把我的颜色改成另一种颜色(强调色)

问题


当你在ForegroundColorSpan或UnderlineSpan后添加ClickableSpan时,SpannableStringBuilder将不会改变颜色和undline。

解决方案


1. 与ClickableSpan

你可以覆盖ClickableSpan内部的updateDrawState方法。 在updateDrawState方法中,您应该删除超级回调。 之后,你应该根据需要修改你的文本绘制。

2. 没有ClickableSpan

添加ForegroundColorSpan来改变文本颜色 Add UnderlineSpan在文本中添加下划线。

其他回答

这是一个帮助函数。当你有多种语言的时候非常有用!

private void setColor(TextView view, String fulltext, String subtext, int color) {
    view.setText(fulltext, TextView.BufferType.SPANNABLE);
    Spannable str = (Spannable) view.getText();
    int i = fulltext.indexOf(subtext);
    str.setSpan(new ForegroundColorSpan(color), i, i + subtext.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}

有一个用于创建Spannable的工厂,并避免强制转换,就像这样:

Spannable span = Spannable.Factory.getInstance().newSpannable("text");

这是一个Kotlin扩展函数

    fun TextView.setColouredSpan(word: String, color: Int) {
        val spannableString = SpannableString(text)
        val start = text.indexOf(word)
        val end = text.indexOf(word) + word.length
        try {
            spannableString.setSpan(ForegroundColorSpan(color), start, end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
            text = spannableString
        } catch (e: IndexOutOfBoundsException) {
         println("'$word' was not not found in TextView text")
    }
}

使用它后,你已经设置你的文本到TextView,就像这样

private val blueberry by lazy { getColor(R.color.blueberry) }

textViewTip.setColouredSpan("Warning", blueberry)

设置你的TextView的文本跨度,并为你的文本定义一个ForegroundColorSpan。

TextView textView = (TextView)findViewById(R.id.mytextview01);    
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");          
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);    
textView.setText(wordtoSpan);

下面的内容非常适合我

    tvPrivacyPolicy = (TextView) findViewById(R.id.tvPrivacyPolicy);
    String originalText = (String)tvPrivacyPolicy.getText();
    int startPosition = 15;
    int endPosition = 31;

    SpannableString spannableStr = new SpannableString(originalText);
    UnderlineSpan underlineSpan = new UnderlineSpan();
    spannableStr.setSpan(underlineSpan, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    ForegroundColorSpan backgroundColorSpan = new ForegroundColorSpan(Color.BLUE);
    spannableStr.setSpan(backgroundColorSpan, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    StyleSpan styleSpanItalic  = new StyleSpan(Typeface.BOLD);

    spannableStr.setSpan(styleSpanItalic, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    tvPrivacyPolicy.setText(spannableStr);

以上代码的输出