Android中设置关键字高亮的方法
Android中设置关键字高亮:
/** * 关键字高亮 * @param str * @param keyWord * @param perfix * @return */ private SpannableStringBuilder highLight(String str, String keyWord, String perfix) { if (str != null && str.length() >= keyWord.length()) { int startPos = str.toLowerCase().indexOf(keyWord.toLowerCase()); if (startPos > -1) { if (perfix != null) { startPos += perfix.length(); str = perfix + str; } int endPos = startPos + keyWord.length(); SpannableStringBuilder style = new SpannableStringBuilder( str); style.setSpan(new ForegroundColorSpan(getResources() .getColor(R.color.search_result_highlight)), startPos, endPos, Spannable.SPAN_EXCLUSIVE_INCLUSIVE); return style; } } return new SpannableStringBuilder(str == null ? "" : ((perfix == null ? "" : perfix) + str)); }
以上为设置关键字高亮的方法,使用方法如下:
textView.setText(highLight(String.valueOf(vo.getNum()), query, null));
注:setTex(CharSequence text) 而SpannableStringBuilder实现了CharSequence 接口。