简体   繁体   English

在WhatsApp Android中将单词标记为

[英]Mark a word like in whatsapp android

I want to mark in yellow some word inside a textview, like whatsapp did in their application. 我想在textview中用黄色标记一个单词,就像whatsapp在其应用程序中所做的那样。 What I've tried was to use html tag: 我尝试过的是使用html标签:

tv.setText("<mark> hello </mark> world"); but it doesn't work, it doesn't mark the word and the tags are part from the text. 但它不起作用,也不会标记单词,并且标记是文本的一部分。

Let's say you have a TextView tv, and you want to set yellow color to the text "hello" of "hello world". 假设您有一个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);

In third line, I'm setting YELLOW color to the word "hello". 在第三行中,我将黄色设置为单词“ hello”。 "hello" starts from index position 0 and ends in index position 5. After setting the span, set the Spannable word as text of TextView tv. “ hello”从索引位置0开始,到索引位置5结束。设置跨度后,将“可扩展”字设置为TextView tv的文本。

Here's documentation on setSpan() 这是有关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. 有关标志含义的解释,请参见Spanned。 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. 一些值得注意的是CharacterStyle和ParagraphStyle以及TextWatcher和SpanWatcher的子类。

Spannable section 可扩展部分

This is the interface for text that has markup objects attached to ranges of it. 这是文本的接口,该文本的接口附加了标记对象。 Not all text classes have mutable markup or text 并非所有的文本类都具有可变的标记或文本

You need to create Spannable and specify color for specific text range. 您需要创建Spannable并为特定文本范围指定颜色。 Like in the following answer: https://stackoverflow.com/a/3514435/1099716 像下面的答案一样: https : //stackoverflow.com/a/3514435/1099716

Try this, 尝试这个,

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

所有其他答案都是相关的,并且本人就是我要使用的答案,但是为了提高灵活性,请注意,还可以将html格式与Html类一起应用:

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

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

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