解决方法
这是我的工作代码,您可以用它来突出显示字符串的某些部分:
private void highlightTextPart(TextView textView,int index,String regularExpression) { String fullText = textView.getText().toString(); int startPos = 0; int endPos = fullText.length(); String[] textParts = fullText.split(regularExpression); if (index < 0 || index > textParts.length - 1) { return; } if (textParts.length > 1) { startPos = fullText.indexOf(textParts[index]); endPos = fullText.indexOf(regularExpression,startPos); if (endPos == -1) { endPos = fullText.length(); } } Spannable spannable = new SpannableString(fullText); ColorStateList blueColor = new ColorStateList(new int[][] { new int[] {}},new int[] { Color.BLUE }); TextAppearanceSpan textAppearanceSpan = new TextAppearanceSpan(null,Typeface.BOLD_ITALIC,-1,blueColor,null); BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(Color.GREEN); spannable.setSpan(textAppearanceSpan,startPos,endPos,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spannable.setSpan(backgroundColorSpan,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(spannable); }
然后在您的活动中,调用如下:
int index = 3; String regularExpression = " "; String text = "Hello StackOverflow From BNK!"; TextView textView = (TextView) findViewById(R.id.textView); if (textView != null) { textView.setText(text); highlightTextPart(textView,index,regularExpression); }