在安卓中设置TextView span的颜色

244

如何在TextView中只设置部分文本的颜色?

我想要做类似Twitter应用的效果,其中一部分文本是蓝色的。请参见下面的图像:

alt text
(来源: twimg.com)

20个回答

6

补充已经被接受的回答,因为所有回答似乎只谈论android.graphics.Color:如果我想要的颜色在res/values/colors.xml中定义怎么办?

例如,考虑在colors.xml中定义的Material Design颜色

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="md_blue_500">#2196F3</color>
</resources>

(android_material_design_colours.xml 是你最好的朋友)

在需要使用Color.BLUE的地方,使用ContextCompat.getColor(getContext(), R.color.md_blue_500)替代它,如下:

wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

变成:

wordtoSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.md_blue_500)), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

我在这里找到了:


6
有一个用于创建Spannable的工厂,并避免强制类型转换,如下所示:
Spannable span = Spannable.Factory.getInstance().newSpannable("text");

1
你能否澄清如何使用SpannableFactory?"text"应该是什么样子的? - Piotr
创建了SpannableFactory的Spannable之后,如何使用它? - MBH

3

这里有些答案已经不是最新的了。因为,你(在大多数情况下)会在链接上添加自定义的点击操作。

此外,根据文档帮助提供的信息,您设定的字符串链接颜色将具有默认值。 “默认链接颜色是主题的强调颜色或者如果在主题中定义了android:textColorLink属性,则为android:textColorLink。”

以下是安全地完成此操作的方法。

 private class CustomClickableSpan extends ClickableSpan {

    private int color = -1;

    public CustomClickableSpan(){
        super();
        if(getContext() != null) {
            color = ContextCompat.getColor(getContext(), R.color.colorPrimaryDark);
        }
    }

    @Override
    public void updateDrawState(@NonNull TextPaint ds) {
        ds.setColor(color != -1 ? color : ds.linkColor);
        ds.setUnderlineText(true);
    }

    @Override
    public void onClick(@NonNull View widget) {
    }
}

然后使用它。

   String text = "my text with action";
    hideText= new SpannableString(text);
    hideText.setSpan(new CustomClickableSpan(){

        @Override
        public void onClick(@NonNull View widget) {
            // your action here !
        }

    }, 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    yourtextview.setText(hideText);
    // don't forget this ! or this will not work !
    yourtextview.setMovementMethod(LinkMovementMethod.getInstance());

希望这能有很大的帮助!


1
以下代码对我来说完美无缺。
    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);

上述代码的输出

enter image description here


1
  • 我遇到了同样的问题。
  • @Dano的答案绝对正确。但是对我不起作用。
  • 之后,我发现我添加了ClickableSpan导致了这个问题。所以它会将我的颜色改变为另一种颜色(强调颜色)

问题


当你在添加ForegroundColorSpanUnderlineSpan之后添加ClickableSpan时,SpannableStringBuilder不会改变颜色和下划线。

解决方案


1. 使用ClickableSpan

  • 您可以在ClickableSpan内覆盖updateDrawState方法。
  • 在updateDrawState方法中,您应该删除超级回调。
  • 之后,您应根据需要修改文本画笔。 enter image description here

2. 不使用ClickableSpan

  • 添加ForegroundColorSpan以更改文本颜色
  • 添加UnderlineSpan以在文本中添加下划线。 enter image description here

1
  1. create textview in ur layout
  2. paste this code in ur MainActivity

    TextView textview=(TextView)findViewById(R.id.textviewid);
    Spannable spannable=new SpannableString("Hello my name is sunil");
    spannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 5, 
    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    textview.setText(spannable);
    //Note:- the 0,5 is the size of colour which u want to give the strring
    //0,5 means it give colour to starting from h and ending with space i.e.(hello), if you want to change size and colour u can easily
    

0
你可以在 Kotlin 中使用扩展函数。
fun CharSequence.colorizeText(
    textPartToColorize: CharSequence,
    @ColorInt color: Int
): CharSequence = SpannableString(this).apply {
    val startIndexOfText = this.indexOf(textPartToColorize.toString())
    setSpan(ForegroundColorSpan(color), startIndexOfText, startIndexOfText.plus(textPartToColorize.length), 0)
}

使用方法:

val colorizedText = "this text will be colorized"
val myTextToColorize = "some text, $colorizedText continue normal text".colorizeText(colorizedText,ContextCompat.getColor(context, R.color.someColor))
viewBinding.myTextView.text = myTextToColorize

0
现在您可以使用CodeView库轻松地用不同的颜色突出显示模式,例如,要用蓝色突出显示文本中的所有URL,您只需要编写:
CodeView codeView = findViewById(R.id.codeview);
codeView.addSyntaxPattern(Patterns.WEB_URL, Color.BLUE);
codeView.setTextHighlighted(text);

CodeView 代码库 URL: https://github.com/amrdeveloper/codeview


0
从开发者文档中,要更改可跨度的颜色和大小:
1-创建一个类:
    class RelativeSizeColorSpan(size: Float,@ColorInt private val color: Int): RelativeSizeSpan(size) {

    override fun updateDrawState(textPaint: TextPaint?) {
        super.updateDrawState(textPaint)
        textPaint?.color = color
    } 
}

使用该类创建您的可扩展字符序列:

    val spannable = SpannableStringBuilder(titleNames)
spannable.setSpan(
    RelativeSizeColorSpan(1.5f, Color.CYAN), // Increase size by 50%
    titleNames.length - microbe.name.length, // start
    titleNames.length, // end
    Spannable.SPAN_EXCLUSIVE_INCLUSIVE
)

-1
First Part **Second Part should be Bold** last Part

这段文本应该使用SpannableString进行更改

import android.graphics.Typeface.BOLD
import android.text.Spannable
import android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
import android.text.SpannableString
import android.text.style.BackgroundColorSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan

val firstPart = "First Part  "
val secondPart = "Second Part should be Bold"
val thirdPart = "  last Part"
val finalString = firstPart + secondPart + thirdPart

val sb: Spannable = SpannableString(finalString).also {
                // ... Change text Colour
                it.setSpan(
                    ForegroundColorSpan(getColor(requireContext(), R.color.pink)),
                    finalString.indexOf(secondPart),
                    finalString.indexOf(secondPart) + secondPart.length,
                    SPAN_EXCLUSIVE_EXCLUSIVE
                )
                // ... Make the text Bold
                it.setSpan(
                    StyleSpan(BOLD),
                    finalString.indexOf(secondPart),
                    finalString.indexOf(secondPart) + secondPart.length,
                    SPAN_EXCLUSIVE_EXCLUSIVE
                )
                // ... Change Background Colour
                it.setSpan(
                    BackgroundColorSpan(getColor(requireContext(), R.color.lightPink)),
                    finalString.indexOf(secondPart) - 1,
                    finalString.indexOf(secondPart) + secondPart.length + 1,
                    SPAN_EXCLUSIVE_EXCLUSIVE
                )
}

yourTextView.text = sb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接