public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setSpecifiedTextsColor(String text, String specifiedTexts) {
List<Integer> sTextsStartList = new ArrayList<>();
int sTextLength = specifiedTexts.length();
String temp = text;
int lengthFront = 0;//记录被找出后前面的字段的长度
int start = -1;
do {
start = temp.indexOf(specifiedTexts);
if (start != -1) {
start = start + lengthFront;
sTextsStartList.add(start);
lengthFront = start + sTextLength;
temp = text.substring(lengthFront);
}
} while (start != -1);
SpannableStringBuilder styledText = new SpannableStringBuilder(text);
for (Integer i : sTextsStartList) {
styledText.setSpan(
new ForegroundColorSpan(getResources().getColor(R.color.f2)),
i,
i + sTextLength,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
setText(styledText);
}
}