Android 搜尋結果中的 搜尋關鍵字 做顏色改變
阿新 • • 發佈:2019-02-15
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); } }