在这篇文章里,用微博中常见的#话题#来做这个高亮关键字的效果。
1、Pattern
private static Pattern getSharpPattern() { if(sharp_Pattern == null) { sharp_Pattern = Pattern.compile("#[^#]+?#"); } return sharp_Pattern; }
public static SpannableString decorateTrendInSpannableString(SpannableString spannableString) { CharacterStyle characterStyle = null; List<Map<String, Object>> list = RegexUtil.getStartAndEndIndex(spannableString.toString(), getSharpPattern()); int size = list.size(); if(list != null && size > 0) { for(int i = 0; i < size; i++) { characterStyle = new ForegroundColorSpan(Color.RED); Map<String, Object> map = list.get(i); spannableString.setSpan(characterStyle, (Integer)map.get("startIndex"), (Integer)map.get("endIndex"), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } return spannableString; }
public static List<Map<String, Object>> getStartAndEndIndex(String sourceStr, Pattern pattern) { List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); Matcher matcher = pattern.matcher(sourceStr); boolean isFind = matcher.find(); while(isFind) { Map<String, Object> map = new HashMap<String, Object>(); map.put("startIndex", matcher.start()); map.put("endIndex", matcher.end()); list.add(map); isFind = matcher.find((Integer)map.get("endIndex") - 1); } return list; }
TextView text_TV = item.getText_TV(); SpannableString text_SS = new SpannableString(status.getText()); text_SS = TextUtil.decorateMentionInSpannableString(status.getText(), text_SS); text_SS = TextUtil.decorateTrendInSpannableString(text_SS); text_SS = TextUtil.decorateURLInSpannableString(text_SS); text_TV.setText(text_SS)