在 whatsapp 中标记一个单词 android

Mark a word like in whatsapp android

我想在文本视图中用黄色标记一些单词,就像 whatsapp 在他们的应用程序中所做的那样。 我试过的是使用 html 标签:

tv.setText("<mark> hello </mark> world"); 但它不起作用,它不标记单词并且标签是文本的一部分。

您需要创建 Spannable 并为特定文本范围指定颜色。就像下面的答案一样:

假设您有一台 TextView 电视,并且您想要为 "hello world" 的文本 "hello" 设置黄色。

TextView tv = (TextView) findViewById(R.id.textView);

Spannable word = new SpannableString("hello world");

word.setSpan(new ForegroundColorSpan(Color.YELLOW), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

tv.setText(word);

在第三行,我将黄色设置为单词 "hello"。 "hello"从index位置0开始,到index位置5结束。设置span后,将Spannable word设置为TextView tv的text。

这是关于 setSpan()

的文档
setSpan (Object what, int start, int end, int flags)

Attach the specified markup object to the range start…end of the text, or move the object to that range if it was already attached elsewhere. See Spanned for an explanation of what the flags mean. The object can be one that has meaning only within your application, or it can be one that the text system will use to affect text display or behavior. Some noteworthy ones are the subclasses of CharacterStyle and ParagraphStyle, and TextWatcher and SpanWatcher.

可跨越的部分

This is the interface for text that has markup objects attached to ranges of it. Not all text classes have mutable markup or text

试试这个,

myTextView.setText(Html.fromHtml(text + "<font color=white>" + CepVizyon.getPhoneCode() + "</font><br><br>"
        + getText(R.string.currentversion) +someString));

所有其他答案都是相关的,并且是我个人会使用的答案,但为了提高灵活性请注意,也可以使用 Html [=] 应用 html 格式15=]:

tv.setText(Html.fromHtml("<font color='red'>Coloured Text</font>"))