2015-09-25 46 views
0

我在textView中有一些文字,我希望文本中的所有短语与Note一样选中它们,并将它们的颜色更改为红色。我怎样才能做到这一点?有没有一种方法呢?如何选择textView中指定的单词

+0

http://stackoverflow.com/questions/32778859/find-next-or-previous-word-on-textview/32780509# 32780509 – penta

+0

你可以在这个[问题]中检查答案(http://stackoverflow.com/questions/8612652/select-a-word-on-a-tap-in-textview-edittext)。 – abozaid

回答

0

试试这个

String text = "Some text in the text view."; 
String searchText = "the"; 
int startPos = -1, endPos = -1; 

if(text.toLowerCase().contains(searchText.toLowerCase())){ 
    startPos = text.toLowerCase().indexOf(searchText.toLowerCase()); 
    endPos = startPos + searchText.length(); 
    Spannable spanText = Spannable.Factory.getInstance().newSpannable(text); 
    if (startPos != -1){ 
     spanText.setSpan(new ForegroundColorSpan(Color.RED), startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
     yourTextView.setText(spanText); 
    } 
} 
0

您可以执行以下操作以突出你的TextView所有的“注”字.. 首先设置来改变颜色的字:

String stringtoChange = "Note"; 

然后更改颜色使用String类的replaceAll方法:

textToHighlight = textToHighlight.replaceAll(stringtoChange, "<font color='red'>" + stringtoChange + "</font>"); 

wh ERE textToHighlight是你的TextView文本,最后设置编辑文本TextView的:

your textView.setText(Html.fromHtml(textToHighlight)); 
相关问题