Android学习札记5:利用Pattern和SpannableString实现高亮关键字效果

在这篇文章里,用微博中常见的#话题#来做这个高亮关键字的效果。

1、Pattern

	private static Pattern getSharpPattern() {
		if(sharp_Pattern == null) {
			sharp_Pattern = Pattern.compile("#[^#]+?#");
		}
		return sharp_Pattern;
	}


2、SpannableString

	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;
	}

注意 characterStyle = new ForegroundColorSpan(Color.RED); 必须写在for循环中,否则会出现只高亮最后一个关键字,而其他的关键字得不到高亮的现象。


3、RegexUtil

	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;
	}

4、应用

		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)

这样做出来的效果是只有高亮关键字而不会给这些关键字添加链接的效果,如果需要链接跳转效果则可用Linkify实现。

你可能感兴趣的:(Android学习札记5:利用Pattern和SpannableString实现高亮关键字效果)