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

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

(来源:twimg.com)


当前回答

现在您可以使用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

其他回答

String text = "I don't like Hasina.";
textView.setText(spannableString(text, 8, 14));

private SpannableString spannableString(String text, int start, int end) {
    SpannableString spannableString = new SpannableString(text);
    ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{0xffa10901});
    TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);

    spannableString.setSpan(highlightSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new BackgroundColorSpan(0xFFFCFF48), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new RelativeSizeSpan(1.5f), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    return spannableString;
}

输出:

现在您可以使用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

另一个答案将非常相似,但不需要设置TextView的文本两次

TextView TV = (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);

TV.setText(wordtoSpan);

通过传递String和Color在文本上设置颜色:

private String getColoredSpanned(String text, String color) {
  String input = "<font color=" + color + ">" + text + "</font>";
  return input;
}

通过调用下面的代码设置TextView / Button / EditText等文本:

TextView:

TextView txtView = (TextView)findViewById(R.id.txtView);

获取彩色字符串:

String name = getColoredSpanned("Hiren", "#800000");

在TextView上设置文本:

txtView.setText(Html.fromHtml(name));

Done

您可以在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