TextView tv = (TextView)findViewById(R.id.tv);
String str ="我要变成红色字体,红色字体,红色字体";
String[] str2 ={"我","变","红"};
tv.setText(turnSomeWordsToRed(str,str2));
public SpannableStringBuilder turnSomeWordsToRed(String OriginStr,String[] strForRed) {
// TODO Auto-generated method stub
SpannableStringBuilder styleStr = new SpannableStringBuilder(strTitle);
for(int i=0;i<strForRed.length;i++) {
int startPosition = strTitle.indexOf(strForRed[i].trim());
int endPosition = startPosition+strForRed[i].length();
styleStr.setSpan(new ForegroundColorSpan(Color.RED), startPosition, endPosition, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}
return styleStr;
}
本文介绍了一种在Android应用中使特定文字变为红色的方法。通过遍历指定字符串并在TextView中使用ForegroundColorSpan来实现文字颜色的变化。此方法适用于需要突出显示部分关键词的应用场景。
1万+

被折叠的 条评论
为什么被折叠?



