Skip to content

Instantly share code, notes, and snippets.

@soe
Forked from NikolaDespotoski/MentionTransformation
Last active August 29, 2015 14:10
Show Gist options
  • Save soe/93b61a6e5c14f46f452f to your computer and use it in GitHub Desktop.
Save soe/93b61a6e5c14f46f452f to your computer and use it in GitHub Desktop.
/**
* Created by nikola on 11/28/14.
*/
public class MentionTransformation implements TransformationMethod {
private int mColor;
private Pattern MENTIONS_PATTERN = Pattern.compile("\\B@[a-z0-9_-]+");
private MentionTransformation(int color) {
mColor = color;
}
public static MentionTransformation getInstance(int color) {
return new MentionTransformation(color);
}
@Override
public CharSequence getTransformation(CharSequence source, View view) {
return findMentions(source.toString());
}
@Override
public void onFocusChanged(View view, CharSequence sourceText, boolean focused, int direction, Rect previouslyFocusedRect) {
}
private SpannableStringBuilder findMentions(String text){
Matcher matcher = MENTIONS_PATTERN.matcher(text);
SpannableStringBuilder spanRange = new SpannableStringBuilder(text);
while(matcher.find()){
String mention = matcher.group();
int startMetion = text.indexOf(mention);
int endMention = startMetion + mention.length();
spanRange.setSpan(new ForegroundColorSpan(mColor), startMetion, endMention, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return spanRange;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment